diff --git a/.idea/rust-crypto-knox.iml b/.idea/rust-crypto-knox.iml new file mode 100644 index 00000000..cf84ae4a --- /dev/null +++ b/.idea/rust-crypto-knox.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 49004566..f787718f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -430,6 +430,7 @@ dependencies = [ "base64 0.22.1", "ed25519-dalek", "futures", + "jni 0.20.0", "libloading", "nitrokey", "once_cell", @@ -1318,6 +1319,20 @@ dependencies = [ "walkdir", ] +[[package]] +name = "jni" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "039022cdf4d7b1cf548d31f60ae783138e5fd42013f6271049d7df7afadef96c" +dependencies = [ + "cesu8", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", +] + [[package]] name = "jni-sys" version = "0.3.0" @@ -2134,7 +2149,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c080146e0cc733697fe500413871142af91bd879641205c2febbe5f982f304e3" dependencies = [ - "jni", + "jni 0.19.0", "paste", "robusta-codegen", "static_assertions", diff --git a/Cargo.toml b/Cargo.toml index 65a9c7b2..b1f688d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ win = ["tpm", "windows"] yubi = ["hsm", "yubikey"] [dependencies] +jni = "0.20.0" anyhow = "*" async-std = "*" futures = "*" diff --git a/Documentation/Doc.md b/Documentation/Doc.md new file mode 100644 index 00000000..186a7ce5 --- /dev/null +++ b/Documentation/Doc.md @@ -0,0 +1,461 @@ + +# Documentation + +## Introduction +This project is part of a student development project at [Hochschule Mannheim (HSMA)](https://www.english.hs-mannheim.de/the-university.html). The project goal is provided by j&s-soft GmbH as part of their open-source project [enmeshed](https://github.com/nmshd). + +### Problem Description +The enmeshed app from j&s-soft GmbH currently secures cryptographic keys in the software. This leads to security vulnerabilities and points of attack. To prevent this, hardware security modules are to be used on which the cryptographic keys are to be securely stored so that they cannot be retrieved even on compromised devices. Our team was tasked with implementing a solution to this problem in the sub-project for Samsung's secure element, the Knox Vault. + +### Product Description +This Repository contains a Wrapper that is used to perform cryptographic operations for mobile applications in a Secure Element (SE) on Android devices. Specifically, this project is focused on Samsung Knox Vault as the SE. The interface to the mobile application is provided in Rust, while the communication with the SE will be done using the Android Keychain API. + + +## Table of Contents +1. [Introduction](#introduction) + - [Problem Description](#problem-description) + - [Product Description](#product-description) +2. [Comprehensive Overview](#comprehensive-overview) + - [Supported Devices](#supported-devices) + - [Performance](#performance) + - [Feature List](#feature-list) + - [Supported Algorithms](#supported-algorithms) +3. [Installation Guide](#installation-guide) + - [Required Software](#required-software) +4. [Usage](#usage) +5. [Architecture](#architecture) + - [Component Diagram](#component-diagram) + - [Components](#components) + - [Libraries](#libraries) +6. [Implementation](#implementation) + - [JNI-Implementation](#jni-implementation) + - [Javadoc](#javadoc) + - [Rustdoc](#rustdoc) +7. [Next Steps](#next-steps) + - [Ideas for our wrapper](#ideas-for-our-wrapper) + - [Ideas for the crypto layer](#ideas-for-the-crypto-layer) +8. [Open Source Project](#open-source-guidelines) +9. [References](#references) + + + +## Comprehensive Overview + +
+ + +### Supported Devices + + +This wrapper should work for all Android devices equipped with a SE, but the focus for our group is specifically on smartphones using Samsung Knox Vault. Therefore, testing will only be done using a Samsung smartphone, and in case there are incompatibilities between device manufacturers, Samsung will take priority. An up-to-date list of devices equipped with Knox Vault can be found [here](https://www.samsungknox.com/en/knox-platform/supported-devices) after selecting Knox Vault in the filter options. As of April 2024, the following devices are equipped with Knox Vault: + +Smartphones +- Samsung Galaxy A 35 / A55 +- Samsung Galaxy S 22 / S23 / S 24 + - the plus / ultra versions as well +- Samsung Galaxy Z Flip 3 / 4 / 5 +- Samsung Galaxy Z Fold 3 / 4 / 5 +- Samsung Galaxy X Cover 7 (Enterprise Edition) + +Tablets +- Galaxy Tab S 8 / S 9 + - the plus, ultra, FE and 5G versions as well +- Galaxy Tab Active 5 (Enterprise Edition) + - the 5G version as well + +We have received a Samsung S22 from j&s-soft and have used this device for testing purposes throughout the project. +
+ +
+ + +### Performance + + +After an extensive performance test, we can conclude that data encryption using AES-256-CBC on the Knox Vault Chip occurs at a rate of approximately 0.11 MB/s. The test showed a variance of 0.58 s². +
+ +
+ + +### Feature List + + +Our project supports the following features: + +- **Saving keys in the strongbox**: All generated keys are stored securely within the strongbox. +- **Encrypt and Decrypt Data**: Utilizing symmetric encryption, our system ensures data confidentiality through encryption and decryption mechanisms. +- **Sign and Verify Data**: We provide functionality for asymmetric signing and verification, ensuring data integrity and authenticity. + +In the following chapter, you will find detailed information on the supported algorithms. +
+ +
+ + +### Supported Algorithms + + +We have provided a list of the supported Algorithms of our project: + +| Algorithm Type | Details | +|----------------|------------------------------------| +| **ECC** | **Curve / Hashing** | +| | secp256r1 / SHA-256 | +| | secp384r1 / SHA-256 | +| | secp521r1 / SHA-256 | +| **RSA** | **Keysize / Hashing / Padding** | +| | 2048 / SHA-256 / PKCS1 | +| | | +| **Symmetric** | **Keysize / Block Mode / Padding** | +| **3DES** | 168 CBC / PKCS7Padding | +| **AES** | 128 / GCM / NoPadding | +| | 128 / CBC / PKCS7Padding | +| | 128 / CTR / NoPadding | +| | 256 / GCM / NoPadding | +| | 256 / CBC / PKCS7Padding | +| | 256 / CTR / NoPadding | +
+ +## Installation Guide + +
+ + +### Required Software + + +If you want to build this project on your own from the source code, these tools are necessary: + +- Android Studio is an IDE specifically for Android app development. While not strictly necessary, having it will make all further steps easier. This guide will assume that you are using it. +- If you plan on modifying the Rust code, it might be smart to also have RustRover installed, since there is no Rust plugin for Android Studio. +- RustUp is the easiest way to install Rust and Cargo. Installation is easiest from within RustRover: After starting to create a new project, there will be a button below the toolchain location selection. Pressing it will install RustUp. Alternatively you can also install RustUp directly from [their page](https://rustup.rs/). +- You will need the Android NDK (Native Development Kit) to build and run the project. The NDK can be installed from within Android Studio: Go to Settings > Languages & Frameworks > Android SDK > SDK Tools and select and install the NDK. +- Cargo and [cargo-ndk](https://docs.rs/crate/cargo-ndk/3.5.4) are necessary to compile the Rust code in a format usable by Android. Cargo should already be installed by RustUp, cargo-ndk can be installed with `cargo install cargo-ndk`. +- You will need to configure cargo further by using this command: `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android` (The "linux" in this command refers to the phone architecture, not your development machine. You can use this command on Windows as well). This will make cargo compile your Rust code in a format suitable for Android architectures +
+ +
+Installing Android Studio + RustRover + +The easiest way to install both IDEs is to use the [JetBrains Toolbox](https://www.jetbrains.com/de-de/toolbox-app/), where you can install both IDEs with a single click each. +Alternatively you can also refer to the [Android CodeLab guide](https://developer.android.com/codelabs/basic-android-kotlin-compose-install-android-studio#0), and the [RustRover download page](https://www.jetbrains.com/rust/nextversion/). + +
+
+ + +### First test in Android Studio + + +The goal of this section is to test Android Studio and run a "Hello World"-App on a real device to confirm that the connection between the computer and phone is working. We will use a USB connection to get the app onto the device, although Wi-Fi should also be possible. This step is not strictly necessary, but eliminates a possible source of error later on. + +- Make sure that USB debugging is enabled on the phone. Refer to [this guide](https://developer.android.com/studio/debug/dev-options) if necessary. +- Install the proper driver for your smartphone on your PC / Laptop according to [this list](https://developer.android.com/studio/run/oem-usb#Drivers). +- Open a new project in Android Studio and select Phone/Tablet on the left and use "Empty Activity" as the template. +- Plug your phone into your PC / Laptop with a USB cable capable of transmitting data. +- You should be able to see your phone's storage in your file explorer. +- In Android Studio, go to "Running Devices" (on the top right by default), click on the plus sign and select your phone. +- The screen of your phone will be mirrored inside Android Studio. +- Build and run your application and open it on the phone. +
+ +
+ + +### Creating a project combining Rust and Java + + +If you already have a project combining Rust and Java, you can skip this section. Otherwise, here is a quick guide for a minimal Project combining the two using [Robusta](https://github.com/giovanniberti/robusta/tree/master). + +- Create a new Android studio project (or use an existing one), that fits your needs for the Android/Java side of your project. +- Create a new folder `rust` in your project files that has the same parent folder as `app`. +- Create a `Cargo.toml` file in that folder with the following content: [`Cargo.toml`](resources/Cargo.toml). +- Create a `lib.rs` file in the same folder with the following content: [`lib.rs`](resources/lib.rs). +- Adjust the package marker for the `RustDef` struct in `lib.rs` on line 14 to contain the correct java package. +
+ +
+Integrating this Repo into your project + +- Fork this Repo and integrate it into the project you created as a submodule. This can be done with: + ``` + git submodule add + git submodule update --init --recursive + ``` +- The two files `CryptoManager.java` and `RustDef.java` in [`src/tpm/android/knox/java`](https://github.com/cep-sose2024/rust-crypto-knox/tree/main/src/tpm/android/knox/java) will need to be moved to the other Java files in your project. By default, this is something like `src/main/java/com/example/example_project`. +- Adjust the `const CLASS_SIGNATURE` in [`src/tpm/android/knox/interface.rs`](https://github.com/cep-sose2024/rust-crypto-knox/blob/main/src/tpm/android/knox/interface.rs) to match the package that you put `RustDef.java` into. For the example above, that would be `const CLASS_SIGNATURE: &str = "com/example/example_project/RustDef";` +
+ +
+ + +### Building and running the project + + +Now you are ready to compile everything. The following command will compile all your Rust code into a dynamic library (`.so`) that can be used by your android app. You will need to run this command within your `rust` folder: + +cargo ndk -t armeabi-v7a -t arm64-v8a -o ../app/src/main/jniLibs build After completing that step, check the directory specified in the command (`app/src/main/jniLibs` in this example). You should find two files `libexampleproject.so` in a sub directory. If so, then the last step was successful. Now you will need to adjust which library Java is looking for. This can be found in `RustDef.java` in line 57. Set the string there to the same as the name of your package in the `rust/Cargo.toml` that you created for your main project. + +Afterwards, you can compile your Java code. You will need to specify the location that the compiled Rust library is in. The easiest way to do that is by specifying the library path when running gradle like this: + +``` +.\gradlew -D java.library.path=app/src/main/jniLibs installDebug +``` +With that, you should have everything complete and compiled the project from scratch. +
+ +## Usage + +Example of how to create a provider and initialize it: +```rust +let instance = SecModules::get_instance( + "test_key".to_owned(), + SecurityModule::Tpm(TpmType::Android(AndroidTpmType::Knox)), + None) +.unwrap(); +let mut module = instance.lock().unwrap(); +``` +To create a key, first you will have to decide which algorithm to use, then set a unique alias for the key. Finally, you can create a key. Here is an example of how that could look like: +```rust +let sym_key = Aes(SymmetricMode::Cbc, Bits128); //Key to be used for symmetric encryption let asym_key = Rsa(Bits2048); //Key to be used for asymmetric encryption + +// creating a symmetric key +let keyname: &str = "sym_key"; +let config = Box::new(KnoxConfig::new(None, + Some(sym_key), + environment.get_java_vm().unwrap()) +.expect("Failed to create KnoxConfig")); +let result = module.create_key(keyname, config); + +// creating an asymmetric key +let keyname: &str = &format!("Asym{}", "asym_key"); +let config = Box::new(KnoxConfig::new(Some(asym_key), + None, + environment.get_java_vm().unwrap())); +module.create_key(keyname, config) +``` +So now that we know how to create keys, let us look at examples of how to use them. +First, we will need to load a key to be used. +```rust +// loading a symmetric key +let config = Box::new(KnoxConfig::new(None, + Some(sym_key), + environment.get_java_vm().unwrap())); +module.load_key(keyname, config); +let config = Box::new(KnoxConfig::new(Some(asym_key), + None, + environment.get_java_vm().unwrap())); +module.load_key(keyname, config) +``` +Now that we loaded the key, we can use encrypt & decrypt, or sign & verify. Here is an example: +```rust +let clear_data: &[u8] = &[1, 0, 255]; //Data to be symmetrically encrypted let sign_data: &[u8] = &[1, 0, 255]; //Data to be signed by the asym key + +// after loading a symmetric key, we can encrypt or decrypt +let enc_data = module.encrypt_data(clear_data) +let dec_data = module.decrypt_data(&enc_data) + +// after loading an asymmetric key, we can sign or verify +let verify_data = module.sign_data(sign_data) +let result_verify = module.verify_signature(&sign_data, &verify_data) +``` + +- If the method call is successful `(Ok(..))`, `Ok(())` is returned. +- In the event of an error `(Err(e))`, the exact error is examined and a corresponding error message is returned. + + + + + + +## Architecture +
+ + +### Component Diagram + + +![component diagram](resources/component_diagram.jpg) +
+ +
+ + +### Components + + +The component diagram illustrates the relationships and interactions between the different classes and modules of the project. Here are the main components: + +- **CryptoManager**: + The `CryptoManager` class handles cryptographic operations within the Android environment. It provides functions for generating and storing symmetric and asymmetric keys in the Android Keystore, as well as for encrypting and decrypting data. Additionally, it enables signing and verifying data using keys stored in the Keystore. + + +- **RustDef**: + The `RustDef` class defines the interface to the cryptographic functions implemented in Rust. It loads the native library. + + +- **interface.rs**: + `interface.rs` serves as the interface between the Rust implementation and the Java side, acting as the counterpart to `RustDef.java`. It facilitates seamless communication between Rust and Java, allowing for the invocation of Rust functions from Java code. This enables developers to leverage the robust cryptographic capabilities implemented in Rust within their Android applications. +
+ +
+ + +### Libraries + + +- #### JNI + +The Java Native Interface (JNI) is a foreign-function interface (FFI) that supports +cross-communication between Java and native languages such as C or Rust. We use it to +communicate between the Rust- and Java parts of the wrapper by calling Java methods from +the Rust environment and passing parameters that way. The JNI is provided by Oracle and tied directly into the JDK. +To find out more about how the exact communication works, check the [JNI Implementation](#JNI-Implementation). +- **KeyStore API** + +The [Android Keystore system](https://developer.android.com/privacy-and-security/keystore) handles the cryptographic keys for us. We went with this over the Knox SDK because it's a better fit for our needs, and even Samsung recommends it in their [Knox Vault White paper](https://image-us.samsung.com/SamsungUS/samsungbusiness/solutions/topics/iot/071421/Knox-Whitepaper-v1.5-20210709.pdf). + +With the Keystore and related APIs, we can use keys to encrypt and decrypt data, as well as sign and verify it. The API also helps us solve the central requirement from j&s-soft, as we can enforce generated cryptographic keys to be saved in the Knox Vault (or any other strongbox). + +The Knox Vault doesn't support all the cryptographic algorithms enabled by the Keystore and other APIs. As we couldn't find any detailed documentation about what the Knox Vault supports, we had to test it out by trial and error. You can see all the algorithms that have passed our tests in the [Supported Algorithms](#supported-algorithms) section. + +You can find out more about the KeyStore API and other APIs that are normally used with it in the following repository: [Android-Security-Reference](https://github.com/doridori/Android-Security-Reference/blob/master/framework/keystore.md). It also has some useful general info about security on Android. +
+ +## Implementation +
+ + +### JNI-Implementation + + +The basic premise of our JNI connection is to have a `JavaVM` passed to the Rust Code. With this reference we are able to call methods provided by the [JNI crate](https://crates.io/crates/jni). Those allow us to call Java functions and pass parameters to them and receive return values and Java exceptions. + +In order to aide type conversion, we are currently using Robusta as a wrapper around the JNI, but we are only using functionality that is provided by the JNI itself, in order to make a future conversion to pure JNI easier. + +From the `JavaVM` that is passed in the `KnoxConfig` struct we are able to obtain a `JNIEnv`. There are two reasons we are passing a `JavaVM` reference instead of a `JNIEnv` reference. First, it makes it a bit easier to use the wrapper, and second, one `JNIEnv` cannot be shared between threads. To make our wrapper more robust, we therefore obtain a `JNIEnv` by calling `javavm.getenv()`. +For us the most important method provided by the JNIEnv is this method: + +```rust +call_static_method(&self, + class: T, name: U, sig: V, args: &[JValue]) -> Result +``` + +This method gets the class definition with the full package name, the name of the method in the class, a signature of the parameters used by the method, and finally the parameters themselves as JValues. + +The class and method name can be determined manually, but the signature should always be automatically generated. To do this, call the following command on the command line: + + ``` javap -s -p path/to/the/java/file.class ``` + +with the compiled `.class` file. This will print all method signatures to the command line, including the name and the parameter signature needed for `sig`. + +The conversion of your parameters to JValues can be done through `JValue::from(jnienv.new_XYZ(xyz))` most of the time. + +The method returns a JValue containing the return type of the Java method that needs to be converted back to Rust data types. If a Java exception is thrown, the method returns an Error. +The conversion back from a JValue is a bit convoluted. In general, this should work: + +```rust +let jobj = result // result is the return value in this case + .l() //Converts to a JObject + .into_inner() as jbyteArray; //converts to a jbyteArray, for other data types equivalent jDataType exist + +let output_vec = jnienv + .convert_byte_array(jobj) //converts the jbyteArray to a Vec, equivalent methods exist for most data types +``` + +Example: + +```rust +call_static_method( +"com/example/vulcans_limes/RustDef", +"create_key", +"(Ljava/lang/String;Ljava/lang/String;)V", +&[JValue::from(jnienv.new_string(key_id).unwrap()), +JValue::from(jnienv.new_string(key_gen_info).unwrap())]); +``` + +
+ +
+ + +### Javadoc + + +All used Java code is documented [here](JavaDoc/index.html). + +
+ +
+ + +### Rustdoc + + +All used Rust code is documented [here](RustDoc/crypto_layer/index.html). + +
+ +## Testing Procedure + +The simplest way to test the code would be to execute Rust unit tests. This is not feasible for this project, because the unit tests would need to be executed on an actual Android phone and cannot be run on an emulator, since the program only functions with the physical HSM. + +Despite the potential benefits of running unit tests on our Android device, we encountered significant challenges due to complexity of setting up a reliable test environment. The time that would have been necessary to invest was needed for more important parts of the project. + +For this reason, we created a test app (which can be found in this repo: [Vulcan's Limes](https://github.com/cep-sose2024/vulcans_limes)) and wrote methods that tests our wrapper by calling the relevant functions of the abstraction layer. This way, it is still possible to confirm functionality without needing to go through the complex process of executing proper Rust unit tests on a smartphone. +Because of the process described above, there is no automated testing process. To execute the tests, you have to compile the test app with the version of the abstraction layer that you want to test. Upon start-up, the function `testMethod()` in [`lib.rs`](https://github.com/cep-sose2024/vulcans_limes/blob/master/app/src/rust/lib.rs) is executed. This method tests all implemented functions, and outputs to the console (which can be viewed with logcat). + +## Next Steps +This chapter is all about looking to the future and thinking about how to take this project in new directions. +
+ + +### Ideas for our wrapper + + +- Check out how many keys the Knox Vault can store and document the result, as apparently the Keystore API does not limit how many keys can be stored. This theoretically means the only limit is the available data storage the Vault has for keys. +- Improve the encrypt and decrypt methods so they can use asymmetric keys. +- Implement a modular key usage handling system. The system should take the information about the key usages when the key gets created, and create it with these specific purposes (e.g. encrypt, decrypt, sign, verify, key lifetime, limited key usages). +- Have a broader spectrum of devices to test on. Knox Vault should technically not be different on the current devices, though in the future that might change. Newer security modules might provide more cryptographic algorithms or performance in the future. +- Obtain a reference to the JavaVM without having to pass it to the crypto layer. +
+ +
+ + +### Ideas for the crypto layer + + +- Encryption and Decryption in Knox Vault is very slow. So creating derived keys for encryption and decryption outside of the security module will speed this process up immensely. The drawback however, this comes with security considerations. +- Implementing some kind of attestation, if possible, so the enmeshed app knows its communicating with a security module, and which security module. (e.g. for our case the Google attestation service) +- A method that lists and returns all the capabilities/supported algorithms the wrapper and security module provide and a method returning all stored key aliases. +- A method that returns the public key of a key pair +- A method that returns metadata about the loaded key like usages, algorithm, etc. + +
+ +## Open Source Guidelines + +This Project is published under an [MIT License](https://github.com/cep-sose2024/rust-crypto-knox/blob/4989f3eb36552537e00fe58cbd29fa95312a6892/LICENSE). + +A Contribution guide can be found [here](https://github.com/nmshd/.github/tree/main). + + + + + +## References +[Samsung Knox White paper](https://image-us.samsung.com/SamsungUS/samsungbusiness/solutions/topics/iot/071421/Knox-Whitepaper-v1.5-20210709.pdf): Hold information about Samsung Knox, but also about the Knox Vault feature. + +[Android Keystore system](https://developer.android.com/privacy-and-security/keystore): Holds information about the Keystore system, how to use the Android keystore, as well as leading to other Android developer documents. + +[Robusta](https://github.com/giovanniberti/robusta/tree/master): The library we use for easier communication between Rust and Java. + +[Java Native Interface (JNI)](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/): Needed for the communication between Rust and Java, Robusta makes using this interface easier for us. + +[j&s-soft GmbH](https://www.js-soft.com/en/): The company behind enmeshed and the client for this project. + +[enmeshed](https://github.com/nmshd): An app developed by j&s-soft that provides secure communication between education providers and individuals. + +[Hochschule Mannheim (HSMA)](https://www.english.hs-mannheim.de/the-university.html): The university of applied science cooperating with j&s-soft for this project. diff --git a/Documentation/JavaDoc/allclasses-index.html b/Documentation/JavaDoc/allclasses-index.html new file mode 100644 index 00000000..726f92ed --- /dev/null +++ b/Documentation/JavaDoc/allclasses-index.html @@ -0,0 +1,67 @@ + + + + +All Classes and Interfaces + + + + + + + + + + + + + + +
+ +
+
+
+

All Classes and Interfaces

+
+
+
Classes
+
+
Class
+
Description
+ +
+
This class provides all the methods we need for communication with the keystore and cryptographic systems.
+
+
+
+
+
+
+ + diff --git a/Documentation/JavaDoc/allpackages-index.html b/Documentation/JavaDoc/allpackages-index.html new file mode 100644 index 00000000..d867f2dd --- /dev/null +++ b/Documentation/JavaDoc/allpackages-index.html @@ -0,0 +1,63 @@ + + + + +All Packages + + + + + + + + + + + + + + +
+ +
+
+
+

All Packages

+
+
Package Summary
+
+
Package
+
Description
+ +
 
+
+
+
+
+ + diff --git a/Documentation/JavaDoc/copy.svg b/Documentation/JavaDoc/copy.svg new file mode 100644 index 00000000..7c46ab15 --- /dev/null +++ b/Documentation/JavaDoc/copy.svg @@ -0,0 +1,33 @@ + + + + + + + + diff --git a/Documentation/JavaDoc/element-list b/Documentation/JavaDoc/element-list new file mode 100644 index 00000000..f14328b9 --- /dev/null +++ b/Documentation/JavaDoc/element-list @@ -0,0 +1 @@ +tpm.android.knox.java diff --git a/Documentation/JavaDoc/help-doc.html b/Documentation/JavaDoc/help-doc.html new file mode 100644 index 00000000..510c6d40 --- /dev/null +++ b/Documentation/JavaDoc/help-doc.html @@ -0,0 +1,177 @@ + + + + +API Help + + + + + + + + + + + + + + +
+ +
+
+

JavaDoc Help

+ +
+
+

Navigation

+Starting from the Overview page, you can browse the documentation using the links in each page, and in the navigation bar at the top of each page. The Index and Search box allow you to navigate to specific declarations and summary pages, including: All Packages, All Classes and Interfaces + +
+
+
+

Kinds of Pages

+The following sections describe the different kinds of pages in this collection. +
+

Package

+

Each package has a page that contains a list of its classes and interfaces, with a summary for each. These pages may contain the following categories:

+
    +
  • Interfaces
  • +
  • Classes
  • +
  • Enum Classes
  • +
  • Exception Classes
  • +
  • Annotation Interfaces
  • +
+
+
+

Class or Interface

+

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a declaration and description, member summary tables, and detailed member descriptions. Entries in each of these sections are omitted if they are empty or not applicable.

+
    +
  • Class Inheritance Diagram
  • +
  • Direct Subclasses
  • +
  • All Known Subinterfaces
  • +
  • All Known Implementing Classes
  • +
  • Class or Interface Declaration
  • +
  • Class or Interface Description
  • +
+
+
    +
  • Nested Class Summary
  • +
  • Enum Constant Summary
  • +
  • Field Summary
  • +
  • Property Summary
  • +
  • Constructor Summary
  • +
  • Method Summary
  • +
  • Required Element Summary
  • +
  • Optional Element Summary
  • +
+
+
    +
  • Enum Constant Details
  • +
  • Field Details
  • +
  • Property Details
  • +
  • Constructor Details
  • +
  • Method Details
  • +
  • Element Details
  • +
+

Note: Annotation interfaces have required and optional elements, but not methods. Only enum classes have enum constants. The components of a record class are displayed as part of the declaration of the record class. Properties are a feature of JavaFX.

+

The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

+
+
+

Other Files

+

Packages and modules may contain pages with additional information related to the declarations nearby.

+
+
+

Tree (Class Hierarchy)

+

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. Classes are organized by inheritance structure starting with java.lang.Object. Interfaces do not inherit from java.lang.Object.

+
    +
  • When viewing the Overview page, clicking on TREE displays the hierarchy for all packages.
  • +
  • When viewing a particular package, class or interface page, clicking on TREE displays the hierarchy for only that package.
  • +
+
+
+

All Packages

+

The All Packages page contains an alphabetic index of all packages contained in the documentation.

+
+
+

All Classes and Interfaces

+

The All Classes and Interfaces page contains an alphabetic index of all classes and interfaces contained in the documentation, including annotation interfaces, enum classes, and record classes.

+
+
+

Index

+

The Index contains an alphabetic index of all classes, interfaces, constructors, methods, and fields in the documentation, as well as summary pages such as All Packages, All Classes and Interfaces.

+
+
+
+This help file applies to API documentation generated by the standard doclet.
+
+
+ + diff --git a/Documentation/JavaDoc/index-all.html b/Documentation/JavaDoc/index-all.html new file mode 100644 index 00000000..fb181592 --- /dev/null +++ b/Documentation/JavaDoc/index-all.html @@ -0,0 +1,119 @@ + + + + +Index + + + + + + + + + + + + + + +
+ +
+
+
+

Index

+
+C D E G L S T V 
All Classes and Interfaces|All Packages +

C

+
+
CryptoManager - Class in tpm.android.knox.java
+
+
This class provides all the methods we need for communication with the keystore and cryptographic systems.
+
+
CryptoManager() - Constructor for class tpm.android.knox.java.CryptoManager
+
+
Constructs a new instance of CryptoManager with the default Android KeyStore.
+
+
+

D

+
+
decryptData(byte[]) - Method in class tpm.android.knox.java.CryptoManager
+
+
Decrypts the given encrypted data using a symmetric key stored in the Android KeyStore.
+
+
+

E

+
+
encryptData(byte[]) - Method in class tpm.android.knox.java.CryptoManager
+
+
Encrypts the given data using a symmetric key stored in the Android KeyStore.
+
+
+

G

+
+
generateKeyPair(String, String) - Method in class tpm.android.knox.java.CryptoManager
+
+
Generates a new asymmetric key pair and saves it into the Android KeyStore.
+
+
genKey(String, String) - Method in class tpm.android.knox.java.CryptoManager
+
+
Generates a new symmetric key and saves it into the Android KeyStore.
+
+
+

L

+
+
loadKey(String) - Method in class tpm.android.knox.java.CryptoManager
+
+
Sets the `KEY_NAME` to the provided key identifier.
+
+
+

S

+
+
signData(byte[]) - Method in class tpm.android.knox.java.CryptoManager
+
+
Signs the given data using a private key stored in the Android KeyStore.
+
+
+

T

+
+
tpm.android.knox.java - package tpm.android.knox.java
+
 
+
+

V

+
+
verifySignature(byte[], byte[]) - Method in class tpm.android.knox.java.CryptoManager
+
+
Verifies the given data against a signature produced by a private key stored in the Android KeyStore.
+
+
+C D E G L S T V 
All Classes and Interfaces|All Packages
+
+
+ + diff --git a/Documentation/JavaDoc/index.html b/Documentation/JavaDoc/index.html new file mode 100644 index 00000000..1d474b00 --- /dev/null +++ b/Documentation/JavaDoc/index.html @@ -0,0 +1,26 @@ + + + + +Generated Documentation (Untitled) + + + + + + + + + + + +
+ +

tpm/android/knox/java/package-summary.html

+
+ + diff --git a/Documentation/JavaDoc/legal/ASSEMBLY_EXCEPTION b/Documentation/JavaDoc/legal/ASSEMBLY_EXCEPTION new file mode 100644 index 00000000..42966666 --- /dev/null +++ b/Documentation/JavaDoc/legal/ASSEMBLY_EXCEPTION @@ -0,0 +1,27 @@ + +OPENJDK ASSEMBLY EXCEPTION + +The OpenJDK source code made available by Oracle America, Inc. (Oracle) at +openjdk.org ("OpenJDK Code") is distributed under the terms of the GNU +General Public License version 2 +only ("GPL2"), with the following clarification and special exception. + + Linking this OpenJDK Code statically or dynamically with other code + is making a combined work based on this library. Thus, the terms + and conditions of GPL2 cover the whole combination. + + As a special exception, Oracle gives you permission to link this + OpenJDK Code with certain code licensed by Oracle as indicated at + https://openjdk.org/legal/exception-modules-2007-05-08.html + ("Designated Exception Modules") to produce an executable, + regardless of the license terms of the Designated Exception Modules, + and to copy and distribute the resulting executable under GPL2, + provided that the Designated Exception Modules continue to be + governed by the licenses under which they were offered by Oracle. + +As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code +to build an executable that includes those portions of necessary code that +Oracle could not provide under GPL2 (or that Oracle has provided under GPL2 +with the Classpath exception). If you modify or add to the OpenJDK code, +that new GPL2 code may still be combined with Designated Exception Modules +if the new code is made subject to this exception by its copyright holder. diff --git a/Documentation/JavaDoc/legal/jquery.md b/Documentation/JavaDoc/legal/jquery.md new file mode 100644 index 00000000..d468b318 --- /dev/null +++ b/Documentation/JavaDoc/legal/jquery.md @@ -0,0 +1,72 @@ +## jQuery v3.6.1 + +### jQuery License +``` +jQuery v 3.6.1 +Copyright OpenJS Foundation and other contributors, https://openjsf.org/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +****************************************** + +The jQuery JavaScript Library v3.6.1 also includes Sizzle.js + +Sizzle.js includes the following license: + +Copyright JS Foundation and other contributors, https://js.foundation/ + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/jquery/sizzle + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +All files located in the node_modules and external directories are +externally maintained libraries used by this software which have their +own licenses; we recommend you read them, as their terms may differ from +the terms above. + +********************* + +``` diff --git a/Documentation/JavaDoc/legal/jqueryUI.md b/Documentation/JavaDoc/legal/jqueryUI.md new file mode 100644 index 00000000..8bda9d7a --- /dev/null +++ b/Documentation/JavaDoc/legal/jqueryUI.md @@ -0,0 +1,49 @@ +## jQuery UI v1.13.2 + +### jQuery UI License +``` +Copyright jQuery Foundation and other contributors, https://jquery.org/ + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/jquery/jquery-ui + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code contained within the demos directory. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +All files located in the node_modules and external directories are +externally maintained libraries used by this software which have their +own licenses; we recommend you read them, as their terms may differ from +the terms above. + +``` diff --git a/Documentation/JavaDoc/link.svg b/Documentation/JavaDoc/link.svg new file mode 100644 index 00000000..7ccc5ed0 --- /dev/null +++ b/Documentation/JavaDoc/link.svg @@ -0,0 +1,31 @@ + + + + + + + + diff --git a/Documentation/JavaDoc/member-search-index.js b/Documentation/JavaDoc/member-search-index.js new file mode 100644 index 00000000..3944b902 --- /dev/null +++ b/Documentation/JavaDoc/member-search-index.js @@ -0,0 +1 @@ +memberSearchIndex = [{"p":"tpm.android.knox.java","c":"CryptoManager","l":"CryptoManager()","u":"%3Cinit%3E()"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"decryptData(byte[])"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"encryptData(byte[])"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"generateKeyPair(String, String)","u":"generateKeyPair(java.lang.String,java.lang.String)"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"genKey(String, String)","u":"genKey(java.lang.String,java.lang.String)"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"loadKey(String)","u":"loadKey(java.lang.String)"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"signData(byte[])"},{"p":"tpm.android.knox.java","c":"CryptoManager","l":"verifySignature(byte[], byte[])","u":"verifySignature(byte[],byte[])"}];updateSearchResults(); \ No newline at end of file diff --git a/Documentation/JavaDoc/module-search-index.js b/Documentation/JavaDoc/module-search-index.js new file mode 100644 index 00000000..0d59754f --- /dev/null +++ b/Documentation/JavaDoc/module-search-index.js @@ -0,0 +1 @@ +moduleSearchIndex = [];updateSearchResults(); \ No newline at end of file diff --git a/Documentation/JavaDoc/overview-tree.html b/Documentation/JavaDoc/overview-tree.html new file mode 100644 index 00000000..b00c3022 --- /dev/null +++ b/Documentation/JavaDoc/overview-tree.html @@ -0,0 +1,70 @@ + + + + +Class Hierarchy + + + + + + + + + + + + + + +
+ +
+
+
+

Hierarchy For All Packages

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+
+ + diff --git a/Documentation/JavaDoc/package-search-index.js b/Documentation/JavaDoc/package-search-index.js new file mode 100644 index 00000000..61a4b15a --- /dev/null +++ b/Documentation/JavaDoc/package-search-index.js @@ -0,0 +1 @@ +packageSearchIndex = [{"l":"All Packages","u":"allpackages-index.html"},{"l":"tpm.android.knox.java"}];updateSearchResults(); \ No newline at end of file diff --git a/Documentation/JavaDoc/resources/glass.png b/Documentation/JavaDoc/resources/glass.png new file mode 100644 index 00000000..a7f591f4 Binary files /dev/null and b/Documentation/JavaDoc/resources/glass.png differ diff --git a/Documentation/JavaDoc/resources/x.png b/Documentation/JavaDoc/resources/x.png new file mode 100644 index 00000000..30548a75 Binary files /dev/null and b/Documentation/JavaDoc/resources/x.png differ diff --git a/Documentation/JavaDoc/script-dir/jquery-3.6.1.min.js b/Documentation/JavaDoc/script-dir/jquery-3.6.1.min.js new file mode 100644 index 00000000..2c69bc90 --- /dev/null +++ b/Documentation/JavaDoc/script-dir/jquery-3.6.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.6.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,y=n.hasOwnProperty,a=y.toString,l=a.call(Object),v={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&v(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!y||!y.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ve(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ye(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ve(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],y=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||y.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||y.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||y.push(".#.+[+~]"),e.querySelectorAll("\\\f"),y.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),y=y.length&&new RegExp(y.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),v=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&v(p,e)?-1:t==C||t.ownerDocument==p&&v(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!y||!y.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),v.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",v.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",v.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),v.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(v.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return B(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=_e(v.pixelPosition,function(e,t){if(t)return t=Be(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return B(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=x(e||this.defaultElement||this)[0],this.element=x(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=x(),this.hoverable=x(),this.focusable=x(),this.classesElementLookup={},e!==this&&(x.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=x(e.style?e.ownerDocument:e.document||e),this.window=x(this.document[0].defaultView||this.document[0].parentWindow)),this.options=x.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:x.noop,_create:x.noop,_init:x.noop,destroy:function(){var i=this;this._destroy(),x.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:x.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return x.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=x.widget.extend({},this.options[t]),n=0;n
"),i=e.children()[0];return x("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.widthC(E(s),E(n))?o.important="horizontal":o.important="vertical",c.using.call(this,t,o)}),l.offset(x.extend(u,{using:t}))})},x.ui.position={fit:{left:function(t,e){var i=e.within,s=i.isWindow?i.scrollLeft:i.offset.left,n=i.width,o=t.left-e.collisionPosition.marginLeft,l=s-o,a=o+e.collisionWidth-n-s;e.collisionWidth>n?0n?0",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(t){var e=x(t.target),i=x(x.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(t){this._delay(function(){x.contains(this.element[0],x.ui.safeActiveElement(this.document[0]))||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(t){var e,i;this.previousFilter||t.clientX===this.lastMousePosition.x&&t.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:t.clientX,y:t.clientY},e=x(t.target).closest(".ui-menu-item"),i=x(t.currentTarget),e[0]===i[0]&&(i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i))))},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=x(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case x.ui.keyCode.PAGE_UP:this.previousPage(t);break;case x.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case x.ui.keyCode.HOME:this._move("first","first",t);break;case x.ui.keyCode.END:this._move("last","last",t);break;case x.ui.keyCode.UP:this.previous(t);break;case x.ui.keyCode.DOWN:this.next(t);break;case x.ui.keyCode.LEFT:this.collapse(t);break;case x.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case x.ui.keyCode.ENTER:case x.ui.keyCode.SPACE:this._activate(t);break;case x.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=x(this),e=t.prev(),i=x("").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=x(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),i=(e=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(e,"ui-menu-item")._addClass(i,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!x.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(i=parseFloat(x.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(x.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-i-s,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&this._isContentEditable(this.element),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=x.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)return i=!1,void(this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault());if(!s){var e=x.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){if(n)return n=!1,void t.preventDefault();this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=x("
    ").appendTo(this._appendTo()).menu({role:null}).hide().attr({unselectable:"on"}).menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault()},menufocus:function(t,e){var i,s;if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),void this.document.one("mousemove",function(){x(t.target).trigger(t.originalEvent)});s=e.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:s})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value),(i=e.item.attr("aria-label")||s.value)&&String.prototype.trim.call(i).length&&(clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(x("
    ").text(i))},100))},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==x.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=x("
    ",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(t){var e=this.menu.element[0];return t.target===this.element[0]||t.target===e||x.contains(e,t.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var t=this.options.appendTo;return t=!(t=!(t=t&&(t.jquery||t.nodeType?x(t):this.document.find(t).eq(0)))||!t[0]?this.element.closest(".ui-front, dialog"):t).length?this.document[0].body:t},_initSource:function(){var i,s,n=this;Array.isArray(this.options.source)?(i=this.options.source,this.source=function(t,e){e(x.ui.autocomplete.filter(i,t.term))}):"string"==typeof this.options.source?(s=this.options.source,this.source=function(t,e){n.xhr&&n.xhr.abort(),n.xhr=x.ajax({url:s,data:t,dataType:"json",success:function(t){e(t)},error:function(){e([])}})}):this.source=this.options.source},_searchTimeout:function(s){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),e=this.menu.element.is(":visible"),i=s.altKey||s.ctrlKey||s.metaKey||s.shiftKey;t&&(e||i)||(this.selectedItem=null,this.search(null,s))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length").append(x("
    ").text(e.label)).appendTo(t)},_move:function(t,e){if(this.menu.element.is(":visible"))return this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),void this.menu.blur()):void this.menu[t](e);this.search(null,e)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){this.isMultiLine&&!this.menu.element.is(":visible")||(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),x.extend(x.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,e){var i=new RegExp(x.ui.autocomplete.escapeRegex(e),"i");return x.grep(t,function(t){return i.test(t.label||t.value||t)})}}),x.widget("ui.autocomplete",x.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(1").text(e))},100))}});x.ui.autocomplete}); \ No newline at end of file diff --git a/Documentation/JavaDoc/script.js b/Documentation/JavaDoc/script.js new file mode 100644 index 00000000..bb9c8a24 --- /dev/null +++ b/Documentation/JavaDoc/script.js @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +var moduleSearchIndex; +var packageSearchIndex; +var typeSearchIndex; +var memberSearchIndex; +var tagSearchIndex; + +var oddRowColor = "odd-row-color"; +var evenRowColor = "even-row-color"; +var sortAsc = "sort-asc"; +var sortDesc = "sort-desc"; +var tableTab = "table-tab"; +var activeTableTab = "active-table-tab"; + +function loadScripts(doc, tag) { + createElem(doc, tag, 'search.js'); + + createElem(doc, tag, 'module-search-index.js'); + createElem(doc, tag, 'package-search-index.js'); + createElem(doc, tag, 'type-search-index.js'); + createElem(doc, tag, 'member-search-index.js'); + createElem(doc, tag, 'tag-search-index.js'); +} + +function createElem(doc, tag, path) { + var script = doc.createElement(tag); + var scriptElement = doc.getElementsByTagName(tag)[0]; + script.src = pathtoroot + path; + scriptElement.parentNode.insertBefore(script, scriptElement); +} + +// Helper for making content containing release names comparable lexicographically +function makeComparable(s) { + return s.toLowerCase().replace(/(\d+)/g, + function(n, m) { + return ("000" + m).slice(-4); + }); +} + +// Switches between two styles depending on a condition +function toggleStyle(classList, condition, trueStyle, falseStyle) { + if (condition) { + classList.remove(falseStyle); + classList.add(trueStyle); + } else { + classList.remove(trueStyle); + classList.add(falseStyle); + } +} + +// Sorts the rows in a table lexicographically by the content of a specific column +function sortTable(header, columnIndex, columns) { + var container = header.parentElement; + var descending = header.classList.contains(sortAsc); + container.querySelectorAll("div.table-header").forEach( + function(header) { + header.classList.remove(sortAsc); + header.classList.remove(sortDesc); + } + ) + var cells = container.children; + var rows = []; + for (var i = columns; i < cells.length; i += columns) { + rows.push(Array.prototype.slice.call(cells, i, i + columns)); + } + var comparator = function(a, b) { + var ka = makeComparable(a[columnIndex].textContent); + var kb = makeComparable(b[columnIndex].textContent); + if (ka < kb) + return descending ? 1 : -1; + if (ka > kb) + return descending ? -1 : 1; + return 0; + }; + var sorted = rows.sort(comparator); + var visible = 0; + sorted.forEach(function(row) { + if (row[0].style.display !== 'none') { + var isEvenRow = visible++ % 2 === 0; + } + row.forEach(function(cell) { + toggleStyle(cell.classList, isEvenRow, evenRowColor, oddRowColor); + container.appendChild(cell); + }) + }); + toggleStyle(header.classList, descending, sortDesc, sortAsc); +} + +// Toggles the visibility of a table category in all tables in a page +function toggleGlobal(checkbox, selected, columns) { + var display = checkbox.checked ? '' : 'none'; + document.querySelectorAll("div.table-tabs").forEach(function(t) { + var id = t.parentElement.getAttribute("id"); + var selectedClass = id + "-tab" + selected; + // if selected is empty string it selects all uncategorized entries + var selectUncategorized = !Boolean(selected); + var visible = 0; + document.querySelectorAll('div.' + id) + .forEach(function(elem) { + if (selectUncategorized) { + if (elem.className.indexOf(selectedClass) === -1) { + elem.style.display = display; + } + } else if (elem.classList.contains(selectedClass)) { + elem.style.display = display; + } + if (elem.style.display === '') { + var isEvenRow = visible++ % (columns * 2) < columns; + toggleStyle(elem.classList, isEvenRow, evenRowColor, oddRowColor); + } + }); + var displaySection = visible === 0 ? 'none' : ''; + t.parentElement.style.display = displaySection; + document.querySelector("li#contents-" + id).style.display = displaySection; + }) +} + +// Shows the elements of a table belonging to a specific category +function show(tableId, selected, columns) { + if (tableId !== selected) { + document.querySelectorAll('div.' + tableId + ':not(.' + selected + ')') + .forEach(function(elem) { + elem.style.display = 'none'; + }); + } + document.querySelectorAll('div.' + selected) + .forEach(function(elem, index) { + elem.style.display = ''; + var isEvenRow = index % (columns * 2) < columns; + toggleStyle(elem.classList, isEvenRow, evenRowColor, oddRowColor); + }); + updateTabs(tableId, selected); +} + +function updateTabs(tableId, selected) { + document.getElementById(tableId + '.tabpanel') + .setAttribute('aria-labelledby', selected); + document.querySelectorAll('button[id^="' + tableId + '"]') + .forEach(function(tab, index) { + if (selected === tab.id || (tableId === selected && index === 0)) { + tab.className = activeTableTab; + tab.setAttribute('aria-selected', true); + tab.setAttribute('tabindex',0); + } else { + tab.className = tableTab; + tab.setAttribute('aria-selected', false); + tab.setAttribute('tabindex',-1); + } + }); +} + +function switchTab(e) { + var selected = document.querySelector('[aria-selected=true]'); + if (selected) { + if ((e.keyCode === 37 || e.keyCode === 38) && selected.previousSibling) { + // left or up arrow key pressed: move focus to previous tab + selected.previousSibling.click(); + selected.previousSibling.focus(); + e.preventDefault(); + } else if ((e.keyCode === 39 || e.keyCode === 40) && selected.nextSibling) { + // right or down arrow key pressed: move focus to next tab + selected.nextSibling.click(); + selected.nextSibling.focus(); + e.preventDefault(); + } + } +} + +var updateSearchResults = function() {}; + +function indexFilesLoaded() { + return moduleSearchIndex + && packageSearchIndex + && typeSearchIndex + && memberSearchIndex + && tagSearchIndex; +} +// Copy the contents of the local snippet to the clipboard +function copySnippet(button) { + copyToClipboard(button.nextElementSibling.innerText); + switchCopyLabel(button, button.firstElementChild); +} +function copyToClipboard(content) { + var textarea = document.createElement("textarea"); + textarea.style.height = 0; + document.body.appendChild(textarea); + textarea.value = content; + textarea.select(); + document.execCommand("copy"); + document.body.removeChild(textarea); +} +function switchCopyLabel(button, span) { + var copied = span.getAttribute("data-copied"); + button.classList.add("visible"); + var initialLabel = span.innerHTML; + span.innerHTML = copied; + setTimeout(function() { + button.classList.remove("visible"); + setTimeout(function() { + if (initialLabel !== copied) { + span.innerHTML = initialLabel; + } + }, 100); + }, 1900); +} +// Workaround for scroll position not being included in browser history (8249133) +document.addEventListener("DOMContentLoaded", function(e) { + var contentDiv = document.querySelector("div.flex-content"); + window.addEventListener("popstate", function(e) { + if (e.state !== null) { + contentDiv.scrollTop = e.state; + } + }); + window.addEventListener("hashchange", function(e) { + history.replaceState(contentDiv.scrollTop, document.title); + }); + var timeoutId; + contentDiv.addEventListener("scroll", function(e) { + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(function() { + history.replaceState(contentDiv.scrollTop, document.title); + }, 100); + }); + if (!location.hash) { + history.replaceState(contentDiv.scrollTop, document.title); + } +}); diff --git a/Documentation/JavaDoc/search-page.js b/Documentation/JavaDoc/search-page.js new file mode 100644 index 00000000..540c90f5 --- /dev/null +++ b/Documentation/JavaDoc/search-page.js @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +"use strict"; +$(function() { + var copy = $("#page-search-copy"); + var expand = $("#page-search-expand"); + var searchLink = $("span#page-search-link"); + var redirect = $("input#search-redirect"); + function setSearchUrlTemplate() { + var href = document.location.href.split(/[#?]/)[0]; + href += "?q=" + "%s"; + if (redirect.is(":checked")) { + href += "&r=1"; + } + searchLink.html(href); + copy[0].onmouseenter(); + } + function copyLink(e) { + copyToClipboard(this.previousSibling.innerText); + switchCopyLabel(this, this.lastElementChild); + } + copy.click(copyLink); + copy[0].onmouseenter = function() {}; + redirect.click(setSearchUrlTemplate); + setSearchUrlTemplate(); + copy.prop("disabled", false); + redirect.prop("disabled", false); + expand.click(function (e) { + var searchInfo = $("div.page-search-info"); + if(this.parentElement.hasAttribute("open")) { + searchInfo.attr("style", "border-width: 0;"); + } else { + searchInfo.attr("style", "border-width: 1px;").height(searchInfo.prop("scrollHeight")); + } + }); +}); +$(window).on("load", function() { + var input = $("#page-search-input"); + var reset = $("#page-search-reset"); + var notify = $("#page-search-notify"); + var resultSection = $("div#result-section"); + var resultContainer = $("div#result-container"); + var searchTerm = ""; + var activeTab = ""; + var fixedTab = false; + var visibleTabs = []; + var feelingLucky = false; + function renderResults(result) { + if (!result.length) { + notify.html(messages.noResult); + } else if (result.length === 1) { + notify.html(messages.oneResult); + } else { + notify.html(messages.manyResults.replace("{0}", result.length)); + } + resultContainer.empty(); + var r = { + "types": [], + "members": [], + "packages": [], + "modules": [], + "searchTags": [] + }; + for (var i in result) { + var item = result[i]; + var arr = r[item.category]; + arr.push(item); + } + if (!activeTab || r[activeTab].length === 0 || !fixedTab) { + Object.keys(r).reduce(function(prev, curr) { + if (r[curr].length > 0 && r[curr][0].score > prev) { + activeTab = curr; + return r[curr][0].score; + } + return prev; + }, 0); + } + if (feelingLucky && activeTab) { + notify.html(messages.redirecting) + var firstItem = r[activeTab][0]; + window.location = getURL(firstItem.indexItem, firstItem.category); + return; + } + if (result.length > 20) { + if (searchTerm[searchTerm.length - 1] === ".") { + if (activeTab === "types" && r["members"].length > r["types"].length) { + activeTab = "members"; + } else if (activeTab === "packages" && r["types"].length > r["packages"].length) { + activeTab = "types"; + } + } + } + var categoryCount = Object.keys(r).reduce(function(prev, curr) { + return prev + (r[curr].length > 0 ? 1 : 0); + }, 0); + visibleTabs = []; + var tabContainer = $("
    ").appendTo(resultContainer); + for (var key in r) { + var id = "#result-tab-" + key.replace("searchTags", "search_tags"); + if (r[key].length) { + var count = r[key].length >= 1000 ? "999+" : r[key].length; + if (result.length > 20 && categoryCount > 1) { + var button = $("").appendTo(tabContainer); + button.click(key, function(e) { + fixedTab = true; + renderResult(e.data, $(this)); + }); + visibleTabs.push(key); + } else { + $("" + categories[key] + + " (" + count + ")").appendTo(tabContainer); + renderTable(key, r[key]).appendTo(resultContainer); + tabContainer = $("
    ").appendTo(resultContainer); + + } + } + } + if (activeTab && result.length > 20 && categoryCount > 1) { + $("button#result-tab-" + activeTab).addClass("active-table-tab"); + renderTable(activeTab, r[activeTab]).appendTo(resultContainer); + } + resultSection.show(); + function renderResult(category, button) { + activeTab = category; + setSearchUrl(); + resultContainer.find("div.summary-table").remove(); + renderTable(activeTab, r[activeTab]).appendTo(resultContainer); + button.siblings().removeClass("active-table-tab"); + button.addClass("active-table-tab"); + } + } + function selectTab(category) { + $("button#result-tab-" + category).click(); + } + function renderTable(category, items) { + var table = $("
    ") + .addClass(category === "modules" + ? "one-column-search-results" + : "two-column-search-results"); + var col1, col2; + if (category === "modules") { + col1 = "Module"; + } else if (category === "packages") { + col1 = "Module"; + col2 = "Package"; + } else if (category === "types") { + col1 = "Package"; + col2 = "Class" + } else if (category === "members") { + col1 = "Class"; + col2 = "Member"; + } else if (category === "searchTags") { + col1 = "Location"; + col2 = "Name"; + } + $("
    " + col1 + "
    ").appendTo(table); + if (category !== "modules") { + $("
    " + col2 + "
    ").appendTo(table); + } + $.each(items, function(index, item) { + var rowColor = index % 2 ? "odd-row-color" : "even-row-color"; + renderItem(item, table, rowColor); + }); + return table; + } + function renderItem(item, table, rowColor) { + var label = getHighlightedText(item.input, item.boundaries, item.prefix.length, item.input.length); + var link = $("") + .attr("href", getURL(item.indexItem, item.category)) + .attr("tabindex", "0") + .addClass("search-result-link") + .html(label); + var container = getHighlightedText(item.input, item.boundaries, 0, item.prefix.length - 1); + if (item.category === "searchTags") { + container = item.indexItem.h || ""; + } + if (item.category !== "modules") { + $("
    ").html(container).addClass("col-plain").addClass(rowColor).appendTo(table); + } + $("
    ").html(link).addClass("col-last").addClass(rowColor).appendTo(table); + } + var timeout; + function schedulePageSearch() { + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(function () { + doPageSearch() + }, 100); + } + function doPageSearch() { + setSearchUrl(); + var term = searchTerm = input.val().trim(); + if (term === "") { + notify.html(messages.enterTerm); + activeTab = ""; + fixedTab = false; + resultContainer.empty(); + resultSection.hide(); + } else { + notify.html(messages.searching); + doSearch({ term: term, maxResults: 1200 }, renderResults); + } + } + function setSearchUrl() { + var query = input.val().trim(); + var url = document.location.pathname; + if (query) { + url += "?q=" + encodeURI(query); + if (activeTab && fixedTab) { + url += "&c=" + activeTab; + } + } + history.replaceState({query: query}, "", url); + } + input.on("input", function(e) { + feelingLucky = false; + schedulePageSearch(); + }); + $(document).keydown(function(e) { + if ((e.ctrlKey || e.metaKey) && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { + if (activeTab && visibleTabs.length > 1) { + var idx = visibleTabs.indexOf(activeTab); + idx += e.key === "ArrowLeft" ? visibleTabs.length - 1 : 1; + selectTab(visibleTabs[idx % visibleTabs.length]); + return false; + } + } + }); + reset.click(function() { + notify.html(messages.enterTerm); + resultSection.hide(); + activeTab = ""; + fixedTab = false; + resultContainer.empty(); + input.val('').focus(); + setSearchUrl(); + }); + input.prop("disabled", false); + reset.prop("disabled", false); + + var urlParams = new URLSearchParams(window.location.search); + if (urlParams.has("q")) { + input.val(urlParams.get("q")) + } + if (urlParams.has("c")) { + activeTab = urlParams.get("c"); + fixedTab = true; + } + if (urlParams.get("r")) { + feelingLucky = true; + } + if (input.val()) { + doPageSearch(); + } else { + notify.html(messages.enterTerm); + } + input.select().focus(); +}); diff --git a/Documentation/JavaDoc/search.html b/Documentation/JavaDoc/search.html new file mode 100644 index 00000000..9a9fcda9 --- /dev/null +++ b/Documentation/JavaDoc/search.html @@ -0,0 +1,71 @@ + + + + +Search + + + + + + + + + + + + + + +
    + +
    +
    +

    Search

    +
    + + +
    +Additional resources +
    +
    +
    +

    The help page provides an introduction to the scope and syntax of JavaDoc search.

    +

    You can use the <ctrl> or <cmd> keys in combination with the left and right arrow keys to switch between result tabs in this page.

    +

    The URL template below may be used to configure this page as a search engine in browsers that support this feature. It has been tested to work in Google Chrome and Mozilla Firefox. Note that other browsers may not support this feature or require a different URL format.

    +link +

    + +

    +
    +

    Loading search index...

    + +
    +
    +
    + + diff --git a/Documentation/JavaDoc/search.js b/Documentation/JavaDoc/search.js new file mode 100644 index 00000000..d3986705 --- /dev/null +++ b/Documentation/JavaDoc/search.js @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +"use strict"; +const messages = { + enterTerm: "Enter a search term", + noResult: "No results found", + oneResult: "Found one result", + manyResults: "Found {0} results", + loading: "Loading search index...", + searching: "Searching...", + redirecting: "Redirecting to first result...", + linkIcon: "Link icon", + linkToSection: "Link to this section" +} +const categories = { + modules: "Modules", + packages: "Packages", + types: "Classes and Interfaces", + members: "Members", + searchTags: "Search Tags" +}; +const highlight = "$&"; +const NO_MATCH = {}; +const MAX_RESULTS = 300; +function checkUnnamed(name, separator) { + return name === "" || !name ? "" : name + separator; +} +function escapeHtml(str) { + return str.replace(//g, ">"); +} +function getHighlightedText(str, boundaries, from, to) { + var start = from; + var text = ""; + for (var i = 0; i < boundaries.length; i += 2) { + var b0 = boundaries[i]; + var b1 = boundaries[i + 1]; + if (b0 >= to || b1 <= from) { + continue; + } + text += escapeHtml(str.slice(start, Math.max(start, b0))); + text += ""; + text += escapeHtml(str.slice(Math.max(start, b0), Math.min(to, b1))); + text += ""; + start = Math.min(to, b1); + } + text += escapeHtml(str.slice(start, to)); + return text; +} +function getURLPrefix(item, category) { + var urlPrefix = ""; + var slash = "/"; + if (category === "modules") { + return item.l + slash; + } else if (category === "packages" && item.m) { + return item.m + slash; + } else if (category === "types" || category === "members") { + if (item.m) { + urlPrefix = item.m + slash; + } else { + $.each(packageSearchIndex, function(index, it) { + if (it.m && item.p === it.l) { + urlPrefix = it.m + slash; + } + }); + } + } + return urlPrefix; +} +function getURL(item, category) { + if (item.url) { + return item.url; + } + var url = getURLPrefix(item, category); + if (category === "modules") { + url += "module-summary.html"; + } else if (category === "packages") { + if (item.u) { + url = item.u; + } else { + url += item.l.replace(/\./g, '/') + "/package-summary.html"; + } + } else if (category === "types") { + if (item.u) { + url = item.u; + } else { + url += checkUnnamed(item.p, "/").replace(/\./g, '/') + item.l + ".html"; + } + } else if (category === "members") { + url += checkUnnamed(item.p, "/").replace(/\./g, '/') + item.c + ".html" + "#"; + if (item.u) { + url += item.u; + } else { + url += item.l; + } + } else if (category === "searchTags") { + url += item.u; + } + item.url = url; + return url; +} +function createMatcher(term, camelCase) { + if (camelCase && !isUpperCase(term)) { + return null; // no need for camel-case matcher for lower case query + } + var pattern = ""; + var upperCase = []; + term.trim().split(/\s+/).forEach(function(w, index, array) { + var tokens = w.split(/(?=[A-Z,.()<>?[\/])/); + for (var i = 0; i < tokens.length; i++) { + var s = tokens[i]; + // ',' and '?' are the only delimiters commonly followed by space in java signatures + pattern += "(" + $.ui.autocomplete.escapeRegex(s).replace(/[,?]/g, "$&\\s*?") + ")"; + upperCase.push(false); + var isWordToken = /\w$/.test(s); + if (isWordToken) { + if (i === tokens.length - 1 && index < array.length - 1) { + // space in query string matches all delimiters + pattern += "(.*?)"; + upperCase.push(isUpperCase(s[0])); + } else { + if (!camelCase && isUpperCase(s) && s.length === 1) { + pattern += "()"; + } else { + pattern += "([a-z0-9$<>?[\\]]*?)"; + } + upperCase.push(isUpperCase(s[0])); + } + } else { + pattern += "()"; + upperCase.push(false); + } + } + }); + var re = new RegExp(pattern, "gi"); + re.upperCase = upperCase; + return re; +} +function findMatch(matcher, input, startOfName, endOfName) { + var from = startOfName; + matcher.lastIndex = from; + var match = matcher.exec(input); + // Expand search area until we get a valid result or reach the beginning of the string + while (!match || match.index + match[0].length < startOfName || endOfName < match.index) { + if (from === 0) { + return NO_MATCH; + } + from = input.lastIndexOf(".", from - 2) + 1; + matcher.lastIndex = from; + match = matcher.exec(input); + } + var boundaries = []; + var matchEnd = match.index + match[0].length; + var score = 5; + var start = match.index; + var prevEnd = -1; + for (var i = 1; i < match.length; i += 2) { + var isUpper = isUpperCase(input[start]); + var isMatcherUpper = matcher.upperCase[i]; + // capturing groups come in pairs, match and non-match + boundaries.push(start, start + match[i].length); + // make sure groups are anchored on a left word boundary + var prevChar = input[start - 1] || ""; + var nextChar = input[start + 1] || ""; + if (start !== 0 && !/[\W_]/.test(prevChar) && !/[\W_]/.test(input[start])) { + if (isUpper && (isLowerCase(prevChar) || isLowerCase(nextChar))) { + score -= 0.1; + } else if (isMatcherUpper && start === prevEnd) { + score -= isUpper ? 0.1 : 1.0; + } else { + return NO_MATCH; + } + } + prevEnd = start + match[i].length; + start += match[i].length + match[i + 1].length; + + // lower score for parts of the name that are missing + if (match[i + 1] && prevEnd < endOfName) { + score -= rateNoise(match[i + 1]); + } + } + // lower score if a type name contains unmatched camel-case parts + if (input[matchEnd - 1] !== "." && endOfName > matchEnd) + score -= rateNoise(input.slice(matchEnd, endOfName)); + score -= rateNoise(input.slice(0, Math.max(startOfName, match.index))); + + if (score <= 0) { + return NO_MATCH; + } + return { + input: input, + score: score, + boundaries: boundaries + }; +} +function isUpperCase(s) { + return s !== s.toLowerCase(); +} +function isLowerCase(s) { + return s !== s.toUpperCase(); +} +function rateNoise(str) { + return (str.match(/([.(])/g) || []).length / 5 + + (str.match(/([A-Z]+)/g) || []).length / 10 + + str.length / 20; +} +function doSearch(request, response) { + var term = request.term.trim(); + var maxResults = request.maxResults || MAX_RESULTS; + if (term.length === 0) { + return this.close(); + } + var matcher = { + plainMatcher: createMatcher(term, false), + camelCaseMatcher: createMatcher(term, true) + } + var indexLoaded = indexFilesLoaded(); + + function getPrefix(item, category) { + switch (category) { + case "packages": + return checkUnnamed(item.m, "/"); + case "types": + return checkUnnamed(item.p, "."); + case "members": + return checkUnnamed(item.p, ".") + item.c + "."; + default: + return ""; + } + } + function useQualifiedName(category) { + switch (category) { + case "packages": + return /[\s/]/.test(term); + case "types": + case "members": + return /[\s.]/.test(term); + default: + return false; + } + } + function searchIndex(indexArray, category) { + var matches = []; + if (!indexArray) { + if (!indexLoaded) { + matches.push({ l: messages.loading, category: category }); + } + return matches; + } + $.each(indexArray, function (i, item) { + var prefix = getPrefix(item, category); + var simpleName = item.l; + var qualifiedName = prefix + simpleName; + var useQualified = useQualifiedName(category); + var input = useQualified ? qualifiedName : simpleName; + var startOfName = useQualified ? prefix.length : 0; + var endOfName = category === "members" && input.indexOf("(", startOfName) > -1 + ? input.indexOf("(", startOfName) : input.length; + var m = findMatch(matcher.plainMatcher, input, startOfName, endOfName); + if (m === NO_MATCH && matcher.camelCaseMatcher) { + m = findMatch(matcher.camelCaseMatcher, input, startOfName, endOfName); + } + if (m !== NO_MATCH) { + m.indexItem = item; + m.prefix = prefix; + m.category = category; + if (!useQualified) { + m.input = qualifiedName; + m.boundaries = m.boundaries.map(function(b) { + return b + prefix.length; + }); + } + matches.push(m); + } + return true; + }); + return matches.sort(function(e1, e2) { + return e2.score - e1.score; + }).slice(0, maxResults); + } + + var result = searchIndex(moduleSearchIndex, "modules") + .concat(searchIndex(packageSearchIndex, "packages")) + .concat(searchIndex(typeSearchIndex, "types")) + .concat(searchIndex(memberSearchIndex, "members")) + .concat(searchIndex(tagSearchIndex, "searchTags")); + + if (!indexLoaded) { + updateSearchResults = function() { + doSearch(request, response); + } + } else { + updateSearchResults = function() {}; + } + response(result); +} +// JQuery search menu implementation +$.widget("custom.catcomplete", $.ui.autocomplete, { + _create: function() { + this._super(); + this.widget().menu("option", "items", "> .result-item"); + // workaround for search result scrolling + this.menu._scrollIntoView = function _scrollIntoView( item ) { + var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; + if ( this._hasScroll() ) { + borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0; + paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0; + offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; + scroll = this.activeMenu.scrollTop(); + elementHeight = this.activeMenu.height() - 26; + itemHeight = item.outerHeight(); + + if ( offset < 0 ) { + this.activeMenu.scrollTop( scroll + offset ); + } else if ( offset + itemHeight > elementHeight ) { + this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); + } + } + }; + }, + _renderMenu: function(ul, items) { + var currentCategory = ""; + var widget = this; + widget.menu.bindings = $(); + $.each(items, function(index, item) { + if (item.category && item.category !== currentCategory) { + ul.append("
  • " + categories[item.category] + "
  • "); + currentCategory = item.category; + } + var li = widget._renderItemData(ul, item); + if (item.category) { + li.attr("aria-label", categories[item.category] + " : " + item.l); + } else { + li.attr("aria-label", item.l); + } + li.attr("class", "result-item"); + }); + ul.append(""); + }, + _renderItem: function(ul, item) { + var li = $("
  • ").appendTo(ul); + var div = $("
    ").appendTo(li); + var label = item.l + ? item.l + : getHighlightedText(item.input, item.boundaries, 0, item.input.length); + var idx = item.indexItem; + if (item.category === "searchTags" && idx && idx.h) { + if (idx.d) { + div.html(label + " (" + idx.h + ")
    " + + idx.d + "
    "); + } else { + div.html(label + " (" + idx.h + ")"); + } + } else { + div.html(label); + } + return li; + } +}); +$(function() { + var expanded = false; + var windowWidth; + function collapse() { + if (expanded) { + $("div#navbar-top").removeAttr("style"); + $("button#navbar-toggle-button") + .removeClass("expanded") + .attr("aria-expanded", "false"); + expanded = false; + } + } + $("button#navbar-toggle-button").click(function (e) { + if (expanded) { + collapse(); + } else { + var navbar = $("div#navbar-top"); + navbar.height(navbar.prop("scrollHeight")); + $("button#navbar-toggle-button") + .addClass("expanded") + .attr("aria-expanded", "true"); + expanded = true; + windowWidth = window.innerWidth; + } + }); + $("ul.sub-nav-list-small li a").click(collapse); + $("input#search-input").focus(collapse); + $("main").click(collapse); + $("section[id] > :header, :header[id], :header:has(a[id])").each(function(idx, el) { + // Create anchor links for headers with an associated id attribute + var hdr = $(el); + var id = hdr.attr("id") || hdr.parent("section").attr("id") || hdr.children("a").attr("id"); + if (id) { + hdr.append(" " + messages.linkIcon +""); + } + }); + $(window).on("orientationchange", collapse).on("resize", function(e) { + if (expanded && windowWidth !== window.innerWidth) collapse(); + }); + var search = $("#search-input"); + var reset = $("#reset-button"); + search.catcomplete({ + minLength: 1, + delay: 200, + source: doSearch, + response: function(event, ui) { + if (!ui.content.length) { + ui.content.push({ l: messages.noResult }); + } else { + $("#search-input").empty(); + } + }, + autoFocus: true, + focus: function(event, ui) { + return false; + }, + position: { + collision: "flip" + }, + select: function(event, ui) { + if (ui.item.indexItem) { + var url = getURL(ui.item.indexItem, ui.item.category); + window.location.href = pathtoroot + url; + $("#search-input").focus(); + } + } + }); + search.val(''); + search.prop("disabled", false); + reset.prop("disabled", false); + reset.click(function() { + search.val('').focus(); + }); + search.focus(); +}); diff --git a/Documentation/JavaDoc/stylesheet.css b/Documentation/JavaDoc/stylesheet.css new file mode 100644 index 00000000..f71489f8 --- /dev/null +++ b/Documentation/JavaDoc/stylesheet.css @@ -0,0 +1,1272 @@ +/* + * Javadoc style sheet + */ + +@import url('resources/fonts/dejavu.css'); + +/* + * These CSS custom properties (variables) define the core color and font + * properties used in this stylesheet. + */ +:root { + /* body, block and code fonts */ + --body-font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; + --block-font-family: 'DejaVu Serif', Georgia, "Times New Roman", Times, serif; + --code-font-family: 'DejaVu Sans Mono', monospace; + /* Base font sizes for body and code elements */ + --body-font-size: 14px; + --code-font-size: 14px; + /* Text colors for body and block elements */ + --body-text-color: #353833; + --block-text-color: #474747; + /* Background colors for various structural elements */ + --body-background-color: #ffffff; + --section-background-color: #f8f8f8; + --detail-background-color: #ffffff; + /* Colors for navigation bar and table captions */ + --navbar-background-color: #4D7A97; + --navbar-text-color: #ffffff; + /* Background color for subnavigation and various headers */ + --subnav-background-color: #dee3e9; + /* Background and text colors for selected tabs and navigation items */ + --selected-background-color: #f8981d; + --selected-text-color: #253441; + --selected-link-color: #1f389c; + /* Background colors for generated tables */ + --even-row-color: #ffffff; + --odd-row-color: #eeeeef; + /* Text color for page title */ + --title-color: #2c4557; + /* Text colors for links */ + --link-color: #4A6782; + --link-color-active: #bb7a2a; + /* Snippet colors */ + --snippet-background-color: #ebecee; + --snippet-text-color: var(--block-text-color); + --snippet-highlight-color: #f7c590; + /* Border colors for structural elements and user defined tables */ + --border-color: #ededed; + --table-border-color: #000000; + /* Search input colors */ + --search-input-background-color: #ffffff; + --search-input-text-color: #000000; + --search-input-placeholder-color: #909090; + /* Highlight color for active search tag target */ + --search-tag-highlight-color: #ffff00; + /* Adjustments for icon and active background colors of copy-to-clipboard buttons */ + --copy-icon-brightness: 100%; + --copy-button-background-color-active: rgba(168, 168, 176, 0.3); + /* Colors for invalid tag notifications */ + --invalid-tag-background-color: #ffe6e6; + --invalid-tag-text-color: #000000; +} +/* + * Styles for individual HTML elements. + * + * These are styles that are specific to individual HTML elements. Changing them affects the style of a particular + * HTML element throughout the page. + */ +body { + background-color:var(--body-background-color); + color:var(--body-text-color); + font-family:var(--body-font-family); + font-size:var(--body-font-size); + margin:0; + padding:0; + height:100%; + width:100%; +} +iframe { + margin:0; + padding:0; + height:100%; + width:100%; + overflow-y:scroll; + border:none; +} +a:link, a:visited { + text-decoration:none; + color:var(--link-color); +} +a[href]:hover, a[href]:focus { + text-decoration:none; + color:var(--link-color-active); +} +pre { + font-family:var(--code-font-family); + font-size:1em; +} +h1 { + font-size:1.428em; +} +h2 { + font-size:1.285em; +} +h3 { + font-size:1.14em; +} +h4 { + font-size:1.072em; +} +h5 { + font-size:1.001em; +} +h6 { + font-size:0.93em; +} +/* Disable font boosting for selected elements */ +h1, h2, h3, h4, h5, h6, div.member-signature { + max-height: 1000em; +} +ul { + list-style-type:disc; +} +code, tt { + font-family:var(--code-font-family); +} +:not(h1, h2, h3, h4, h5, h6) > code, +:not(h1, h2, h3, h4, h5, h6) > tt { + font-size:var(--code-font-size); + padding-top:4px; + margin-top:8px; + line-height:1.4em; +} +dt code { + font-family:var(--code-font-family); + font-size:1em; + padding-top:4px; +} +.summary-table dt code { + font-family:var(--code-font-family); + font-size:1em; + vertical-align:top; + padding-top:4px; +} +sup { + font-size:8px; +} +button { + font-family: var(--body-font-family); + font-size: 1em; +} +/* + * Styles for HTML generated by javadoc. + * + * These are style classes that are used by the standard doclet to generate HTML documentation. + */ + +/* + * Styles for document title and copyright. + */ +.about-language { + float:right; + padding:0 21px 8px 8px; + font-size:0.915em; + margin-top:-9px; + height:2.9em; +} +.legal-copy { + margin-left:.5em; +} +/* + * Styles for navigation bar. + */ +@media screen { + div.flex-box { + position:fixed; + display:flex; + flex-direction:column; + height: 100%; + width: 100%; + } + header.flex-header { + flex: 0 0 auto; + } + div.flex-content { + flex: 1 1 auto; + overflow-y: auto; + } +} +.top-nav { + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); + float:left; + width:100%; + clear:right; + min-height:2.8em; + padding:10px 0 0 0; + overflow:hidden; + font-size:0.857em; +} +button#navbar-toggle-button { + display:none; +} +ul.sub-nav-list-small { + display: none; +} +.sub-nav { + background-color:var(--subnav-background-color); + float:left; + width:100%; + overflow:hidden; + font-size:0.857em; +} +.sub-nav div { + clear:left; + float:left; + padding:6px; + text-transform:uppercase; +} +.sub-nav .sub-nav-list { + padding-top:4px; +} +ul.nav-list { + display:block; + margin:0 25px 0 0; + padding:0; +} +ul.sub-nav-list { + float:left; + margin:0 25px 0 0; + padding:0; +} +ul.nav-list li { + list-style:none; + float:left; + padding: 5px 6px; + text-transform:uppercase; +} +.sub-nav .nav-list-search { + float:right; + margin:0; + padding:6px; + clear:none; + text-align:right; + position:relative; +} +ul.sub-nav-list li { + list-style:none; + float:left; +} +.top-nav a:link, .top-nav a:active, .top-nav a:visited { + color:var(--navbar-text-color); + text-decoration:none; + text-transform:uppercase; +} +.top-nav a:hover { + color:var(--link-color-active); +} +.nav-bar-cell1-rev { + background-color:var(--selected-background-color); + color:var(--selected-text-color); + margin: auto 5px; +} +.skip-nav { + position:absolute; + top:auto; + left:-9999px; + overflow:hidden; +} +/* + * Hide navigation links and search box in print layout + */ +@media print { + ul.nav-list, div.sub-nav { + display:none; + } +} +/* + * Styles for page header. + */ +.title { + color:var(--title-color); + margin:10px 0; +} +.sub-title { + margin:5px 0 0 0; +} +ul.contents-list { + margin: 0 0 15px 0; + padding: 0; + list-style: none; +} +ul.contents-list li { + font-size:0.93em; +} +/* + * Styles for headings. + */ +body.class-declaration-page .summary h2, +body.class-declaration-page .details h2, +body.class-use-page h2, +body.module-declaration-page .block-list h2 { + font-style: italic; + padding:0; + margin:15px 0; +} +body.class-declaration-page .summary h3, +body.class-declaration-page .details h3, +body.class-declaration-page .summary .inherited-list h2 { + background-color:var(--subnav-background-color); + border:1px solid var(--border-color); + margin:0 0 6px -8px; + padding:7px 5px; +} +/* + * Styles for page layout containers. + */ +main { + clear:both; + padding:10px 20px; + position:relative; +} +dl.notes > dt { + font-family: var(--body-font-family); + font-size:0.856em; + font-weight:bold; + margin:10px 0 0 0; + color:var(--body-text-color); +} +dl.notes > dd { + margin:5px 10px 10px 0; + font-size:1em; + font-family:var(--block-font-family) +} +dl.name-value > dt { + margin-left:1px; + font-size:1.1em; + display:inline; + font-weight:bold; +} +dl.name-value > dd { + margin:0 0 0 1px; + font-size:1.1em; + display:inline; +} +/* + * Styles for lists. + */ +li.circle { + list-style:circle; +} +ul.horizontal li { + display:inline; + font-size:0.9em; +} +div.inheritance { + margin:0; + padding:0; +} +div.inheritance div.inheritance { + margin-left:2em; +} +ul.block-list, +ul.details-list, +ul.member-list, +ul.summary-list { + margin:10px 0 10px 0; + padding:0; +} +ul.block-list > li, +ul.details-list > li, +ul.member-list > li, +ul.summary-list > li { + list-style:none; + margin-bottom:15px; + line-height:1.4; +} +ul.ref-list { + padding:0; + margin:0; +} +ul.ref-list > li { + list-style:none; +} +.summary-table dl, .summary-table dl dt, .summary-table dl dd { + margin-top:0; + margin-bottom:1px; +} +ul.tag-list, ul.tag-list-long { + padding-left: 0; + list-style: none; +} +ul.tag-list li { + display: inline; +} +ul.tag-list li:not(:last-child):after, +ul.tag-list-long li:not(:last-child):after +{ + content: ", "; + white-space: pre-wrap; +} +ul.preview-feature-list { + list-style: none; + margin:0; + padding:0.1em; + line-height: 1.6em; +} +/* + * Styles for tables. + */ +.summary-table, .details-table { + width:100%; + border-spacing:0; + border:1px solid var(--border-color); + border-top:0; + padding:0; +} +.caption { + position:relative; + text-align:left; + background-repeat:no-repeat; + color:var(--selected-text-color); + clear:none; + overflow:hidden; + padding: 10px 0 0 1px; + margin:0; +} +.caption a:link, .caption a:visited { + color:var(--selected-link-color); +} +.caption a:hover, +.caption a:active { + color:var(--navbar-text-color); +} +.caption span { + font-weight:bold; + white-space:nowrap; + padding:5px 12px 7px 12px; + display:inline-block; + float:left; + background-color:var(--selected-background-color); + border: none; + height:16px; +} +div.table-tabs { + padding:10px 0 0 1px; + margin:10px 0 0 0; +} +div.table-tabs > button { + border: none; + cursor: pointer; + padding: 5px 12px 7px 12px; + font-weight: bold; + margin-right: 8px; +} +div.table-tabs > .active-table-tab { + background: var(--selected-background-color); + color: var(--selected-text-color); +} +div.table-tabs > button.table-tab { + background: var(--navbar-background-color); + color: var(--navbar-text-color); +} +.two-column-search-results { + display: grid; + grid-template-columns: minmax(400px, max-content) minmax(400px, auto); +} +div.checkboxes { + line-height: 2em; +} +div.checkboxes > span { + margin-left: 10px; +} +div.checkboxes > label { + margin-left: 8px; + white-space: nowrap; +} +div.checkboxes > label > input { + margin: 0 2px; +} +.two-column-summary { + display: grid; + grid-template-columns: minmax(25%, max-content) minmax(25%, auto); +} +.three-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(20%, max-content) minmax(20%, auto); +} +.three-column-release-summary { + display: grid; + grid-template-columns: minmax(40%, max-content) minmax(10%, max-content) minmax(40%, auto); +} +.four-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(15%, max-content) minmax(15%, max-content) minmax(15%, auto); +} +@media screen and (max-width: 1000px) { + .four-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(15%, auto); + } +} +@media screen and (max-width: 800px) { + .two-column-search-results { + display: grid; + grid-template-columns: minmax(40%, max-content) minmax(40%, auto); + } + .three-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(25%, auto); + } + .three-column-release-summary { + display: grid; + grid-template-columns: minmax(70%, max-content) minmax(30%, max-content) + } + .three-column-summary .col-last, + .three-column-release-summary .col-last{ + grid-column-end: span 2; + } +} +@media screen and (max-width: 600px) { + .two-column-summary { + display: grid; + grid-template-columns: 1fr; + } +} +.summary-table > div, .details-table > div { + text-align:left; + padding: 8px 3px 3px 7px; + overflow-x: auto; + scrollbar-width: thin; +} +.col-first, .col-second, .col-last, .col-constructor-name, .col-summary-item-name { + vertical-align:top; + padding-right:0; + padding-top:8px; + padding-bottom:3px; +} +.table-header { + background:var(--subnav-background-color); + font-weight: bold; +} +/* Sortable table columns */ +.table-header[onclick] { + cursor: pointer; +} +.table-header[onclick]::after { + content:""; + display:inline-block; + background-image:url('data:image/svg+xml; utf8, \ + \ + '); + background-size:100% 100%; + width:9px; + height:14px; + margin-left:4px; + margin-bottom:-3px; +} +.table-header[onclick].sort-asc::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); + +} +.table-header[onclick].sort-desc::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); +} +.col-first, .col-first { + font-size:0.93em; +} +.col-second, .col-second, .col-last, .col-constructor-name, .col-summary-item-name, .col-last { + font-size:0.93em; +} +.col-first, .col-second, .col-constructor-name { + vertical-align:top; + overflow: auto; +} +.col-last { + white-space:normal; +} +.col-first a:link, .col-first a:visited, +.col-second a:link, .col-second a:visited, +.col-first a:link, .col-first a:visited, +.col-second a:link, .col-second a:visited, +.col-constructor-name a:link, .col-constructor-name a:visited, +.col-summary-item-name a:link, .col-summary-item-name a:visited { + font-weight:bold; +} +.even-row-color, .even-row-color .table-header { + background-color:var(--even-row-color); +} +.odd-row-color, .odd-row-color .table-header { + background-color:var(--odd-row-color); +} +/* + * Styles for contents. + */ +div.block { + font-size:var(--body-font-size); + font-family:var(--block-font-family); +} +.col-last div { + padding-top:0; +} +.col-last a { + padding-bottom:3px; +} +.module-signature, +.package-signature, +.type-signature, +.member-signature { + font-family:var(--code-font-family); + font-size:1em; + margin:14px 0; + white-space: pre-wrap; +} +.module-signature, +.package-signature, +.type-signature { + margin-top: 0; +} +.member-signature .type-parameters-long, +.member-signature .parameters, +.member-signature .exceptions { + display: inline-block; + vertical-align: top; + white-space: pre; +} +.member-signature .type-parameters { + white-space: normal; +} +/* + * Styles for formatting effect. + */ +.source-line-no { + /* Color of line numbers in source pages can be set via custom property below */ + color:var(--source-linenumber-color, green); + padding:0 30px 0 0; +} +.block { + display:block; + margin:0 10px 5px 0; + color:var(--block-text-color); +} +.deprecated-label, .description-from-type-label, .implementation-label, .member-name-link, +.module-label-in-package, .module-label-in-type, .package-label-in-type, +.package-hierarchy-label, .type-name-label, .type-name-link, .search-tag-link, .preview-label { + font-weight:bold; +} +.deprecation-comment, .help-footnote, .preview-comment { + font-style:italic; +} +.deprecation-block { + font-size:1em; + font-family:var(--block-font-family); + border-style:solid; + border-width:thin; + border-radius:10px; + padding:10px; + margin-bottom:10px; + margin-right:10px; + display:inline-block; +} +.preview-block { + font-size:1em; + font-family:var(--block-font-family); + border-style:solid; + border-width:thin; + border-radius:10px; + padding:10px; + margin-bottom:10px; + margin-right:10px; + display:inline-block; +} +div.block div.deprecation-comment { + font-style:normal; +} +details.invalid-tag, span.invalid-tag { + font-size:1em; + font-family:var(--block-font-family); + color: var(--invalid-tag-text-color); + background: var(--invalid-tag-background-color); + border: thin solid var(--table-border-color); + border-radius:2px; + padding: 2px 4px; + display:inline-block; +} +details summary { + cursor: pointer; +} +/* + * Styles specific to HTML5 elements. + */ +main, nav, header, footer, section { + display:block; +} +/* + * Styles for javadoc search. + */ +.ui-state-active { + /* Overrides the color of selection used in jQuery UI */ + background: var(--selected-background-color); + border: 1px solid var(--selected-background-color); + color: var(--selected-text-color); +} +.ui-autocomplete-category { + font-weight:bold; + font-size:15px; + padding:7px 0 7px 3px; + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); +} +.ui-autocomplete { + max-height:85%; + max-width:65%; + overflow-y:auto; + overflow-x:auto; + scrollbar-width: thin; + white-space:nowrap; + box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23); +} +ul.ui-autocomplete { + position:fixed; + z-index:1; + background-color: var(--body-background-color); +} +ul.ui-autocomplete li { + float:left; + clear:both; + min-width:100%; +} +ul.ui-autocomplete li.ui-static-link { + position:sticky; + bottom:0; + left:0; + background: var(--subnav-background-color); + padding: 5px 0; + font-family: var(--body-font-family); + font-size: 0.93em; + font-weight: bolder; + z-index: 2; +} +li.ui-static-link a, li.ui-static-link a:visited { + text-decoration:none; + color:var(--link-color); + float:right; + margin-right:20px; +} +.ui-autocomplete .result-item { + font-size: inherit; +} +.ui-autocomplete .result-highlight { + font-weight:bold; +} +#search-input, #page-search-input { + background-image:url('resources/glass.png'); + background-size:13px; + background-repeat:no-repeat; + background-position:2px 3px; + background-color: var(--search-input-background-color); + color: var(--search-input-text-color); + border-color: var(--border-color); + padding-left:20px; + width: 250px; + margin: 0; +} +#search-input { + margin-left: 4px; +} +#reset-button { + background-color: transparent; + background-image:url('resources/x.png'); + background-repeat:no-repeat; + background-size:contain; + border:0; + border-radius:0; + width:12px; + height:12px; + position:absolute; + right:12px; + top:10px; + font-size:0; +} +::placeholder { + color:var(--search-input-placeholder-color); + opacity: 1; +} +.search-tag-desc-result { + font-style:italic; + font-size:11px; +} +.search-tag-holder-result { + font-style:italic; + font-size:12px; +} +.search-tag-result:target { + background-color:var(--search-tag-highlight-color); +} +details.page-search-details { + display: inline-block; +} +div#result-container { + font-size: 1em; +} +div#result-container a.search-result-link { + padding: 0; + margin: 4px 0; + width: 100%; +} +#result-container .result-highlight { + font-weight:bolder; +} +.page-search-info { + background-color: var(--subnav-background-color); + border-radius: 3px; + border: 0 solid var(--border-color); + padding: 0 8px; + overflow: hidden; + height: 0; + transition: all 0.2s ease; +} +div.table-tabs > button.table-tab { + background: var(--navbar-background-color); + color: var(--navbar-text-color); +} +.page-search-header { + padding: 5px 12px 7px 12px; + font-weight: bold; + margin-right: 3px; + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); + display: inline-block; +} +button.page-search-header { + border: none; + cursor: pointer; +} +span#page-search-link { + text-decoration: underline; +} +.module-graph span, .sealed-graph span { + display:none; + position:absolute; +} +.module-graph:hover span, .sealed-graph:hover span { + display:block; + margin: -100px 0 0 100px; + z-index: 1; +} +.inherited-list { + margin: 10px 0 10px 0; +} +section.class-description { + line-height: 1.4; +} +.summary section[class$="-summary"], .details section[class$="-details"], +.class-uses .detail, .serialized-class-details { + padding: 0 20px 5px 10px; + border: 1px solid var(--border-color); + background-color: var(--section-background-color); +} +.inherited-list, section[class$="-details"] .detail { + padding:0 0 5px 8px; + background-color:var(--detail-background-color); + border:none; +} +.vertical-separator { + padding: 0 5px; +} +ul.help-section-list { + margin: 0; +} +ul.help-subtoc > li { + display: inline-block; + padding-right: 5px; + font-size: smaller; +} +ul.help-subtoc > li::before { + content: "\2022" ; + padding-right:2px; +} +.help-note { + font-style: italic; +} +/* + * Indicator icon for external links. + */ +main a[href*="://"]::after { + content:""; + display:inline-block; + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); + background-size:100% 100%; + width:7px; + height:7px; + margin-left:2px; + margin-bottom:4px; +} +main a[href*="://"]:hover::after, +main a[href*="://"]:focus::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); +} +/* + * Styles for header/section anchor links + */ +a.anchor-link { + opacity: 0; + transition: opacity 0.1s; +} +:hover > a.anchor-link { + opacity: 80%; +} +a.anchor-link:hover, +a.anchor-link:focus-visible, +a.anchor-link.visible { + opacity: 100%; +} +a.anchor-link > img { + width: 0.9em; + height: 0.9em; +} +/* + * Styles for copy-to-clipboard buttons + */ +button.copy { + opacity: 70%; + border: none; + border-radius: 3px; + position: relative; + background:none; + transition: opacity 0.3s; + cursor: pointer; +} +:hover > button.copy { + opacity: 80%; +} +button.copy:hover, +button.copy:active, +button.copy:focus-visible, +button.copy.visible { + opacity: 100%; +} +button.copy img { + position: relative; + background: none; + filter: brightness(var(--copy-icon-brightness)); +} +button.copy:active { + background-color: var(--copy-button-background-color-active); +} +button.copy span { + color: var(--body-text-color); + position: relative; + top: -0.1em; + transition: all 0.1s; + font-size: 0.76rem; + line-height: 1.2em; + opacity: 0; +} +button.copy:hover span, +button.copy:focus-visible span, +button.copy.visible span { + opacity: 100%; +} +/* search page copy button */ +button#page-search-copy { + margin-left: 0.4em; + padding:0.3em; + top:0.13em; +} +button#page-search-copy img { + width: 1.2em; + height: 1.2em; + padding: 0.01em 0; + top: 0.15em; +} +button#page-search-copy span { + color: var(--body-text-color); + line-height: 1.2em; + padding: 0.2em; + top: -0.18em; +} +div.page-search-info:hover button#page-search-copy span { + opacity: 100%; +} +/* snippet copy button */ +button.snippet-copy { + position: absolute; + top: 6px; + right: 6px; + height: 1.7em; + padding: 2px; +} +button.snippet-copy img { + width: 18px; + height: 18px; + padding: 0.05em 0; +} +button.snippet-copy span { + line-height: 1.2em; + padding: 0.2em; + position: relative; + top: -0.5em; +} +div.snippet-container:hover button.snippet-copy span { + opacity: 100%; +} +/* + * Styles for user-provided tables. + * + * borderless: + * No borders, vertical margins, styled caption. + * This style is provided for use with existing doc comments. + * In general, borderless tables should not be used for layout purposes. + * + * plain: + * Plain borders around table and cells, vertical margins, styled caption. + * Best for small tables or for complex tables for tables with cells that span + * rows and columns, when the "striped" style does not work well. + * + * striped: + * Borders around the table and vertical borders between cells, striped rows, + * vertical margins, styled caption. + * Best for tables that have a header row, and a body containing a series of simple rows. + */ + +table.borderless, +table.plain, +table.striped { + margin-top: 10px; + margin-bottom: 10px; +} +table.borderless > caption, +table.plain > caption, +table.striped > caption { + font-weight: bold; + font-size: smaller; +} +table.borderless th, table.borderless td, +table.plain th, table.plain td, +table.striped th, table.striped td { + padding: 2px 5px; +} +table.borderless, +table.borderless > thead > tr > th, table.borderless > tbody > tr > th, table.borderless > tr > th, +table.borderless > thead > tr > td, table.borderless > tbody > tr > td, table.borderless > tr > td { + border: none; +} +table.borderless > thead > tr, table.borderless > tbody > tr, table.borderless > tr { + background-color: transparent; +} +table.plain { + border-collapse: collapse; + border: 1px solid var(--table-border-color); +} +table.plain > thead > tr, table.plain > tbody tr, table.plain > tr { + background-color: transparent; +} +table.plain > thead > tr > th, table.plain > tbody > tr > th, table.plain > tr > th, +table.plain > thead > tr > td, table.plain > tbody > tr > td, table.plain > tr > td { + border: 1px solid var(--table-border-color); +} +table.striped { + border-collapse: collapse; + border: 1px solid var(--table-border-color); +} +table.striped > thead { + background-color: var(--subnav-background-color); +} +table.striped > thead > tr > th, table.striped > thead > tr > td { + border: 1px solid var(--table-border-color); +} +table.striped > tbody > tr:nth-child(even) { + background-color: var(--odd-row-color) +} +table.striped > tbody > tr:nth-child(odd) { + background-color: var(--even-row-color) +} +table.striped > tbody > tr > th, table.striped > tbody > tr > td { + border-left: 1px solid var(--table-border-color); + border-right: 1px solid var(--table-border-color); +} +table.striped > tbody > tr > th { + font-weight: normal; +} +/** + * Tweak style for small screens. + */ +@media screen and (max-width: 920px) { + header.flex-header { + max-height: 100vh; + overflow-y: auto; + } + div#navbar-top { + height: 2.8em; + transition: height 0.35s ease; + } + ul.nav-list { + display: block; + width: 40%; + float:left; + clear: left; + margin: 10px 0 0 0; + padding: 0; + } + ul.nav-list li { + float: none; + padding: 6px; + margin-left: 10px; + margin-top: 2px; + } + ul.sub-nav-list-small { + display:block; + height: 100%; + width: 50%; + float: right; + clear: right; + background-color: var(--subnav-background-color); + color: var(--body-text-color); + margin: 6px 0 0 0; + padding: 0; + } + ul.sub-nav-list-small ul { + padding-left: 20px; + } + ul.sub-nav-list-small a:link, ul.sub-nav-list-small a:visited { + color:var(--link-color); + } + ul.sub-nav-list-small a:hover { + color:var(--link-color-active); + } + ul.sub-nav-list-small li { + list-style:none; + float:none; + padding: 6px; + margin-top: 1px; + text-transform:uppercase; + } + ul.sub-nav-list-small > li { + margin-left: 10px; + } + ul.sub-nav-list-small li p { + margin: 5px 0; + } + div#navbar-sub-list { + display: none; + } + .top-nav a:link, .top-nav a:active, .top-nav a:visited { + display: block; + } + button#navbar-toggle-button { + width: 3.4em; + height: 2.8em; + background-color: transparent; + display: block; + float: left; + border: 0; + margin: 0 10px; + cursor: pointer; + font-size: 10px; + } + button#navbar-toggle-button .nav-bar-toggle-icon { + display: block; + width: 24px; + height: 3px; + margin: 1px 0 4px 0; + border-radius: 2px; + transition: all 0.1s; + background-color: var(--navbar-text-color); + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(1) { + transform: rotate(45deg); + transform-origin: 10% 10%; + width: 26px; + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(2) { + opacity: 0; + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(3) { + transform: rotate(-45deg); + transform-origin: 10% 90%; + width: 26px; + } +} +@media screen and (max-width: 800px) { + .about-language { + padding-right: 16px; + } + ul.nav-list li { + margin-left: 5px; + } + ul.sub-nav-list-small > li { + margin-left: 5px; + } + main { + padding: 10px; + } + .summary section[class$="-summary"], .details section[class$="-details"], + .class-uses .detail, .serialized-class-details { + padding: 0 8px 5px 8px; + } + body { + -webkit-text-size-adjust: none; + } +} +@media screen and (max-width: 400px) { + .about-language { + font-size: 10px; + padding-right: 12px; + } +} +@media screen and (max-width: 400px) { + .nav-list-search { + width: 94%; + } + #search-input, #page-search-input { + width: 70%; + } +} +@media screen and (max-width: 320px) { + .nav-list-search > label { + display: none; + } + .nav-list-search { + width: 90%; + } + #search-input, #page-search-input { + width: 80%; + } +} + +pre.snippet { + background-color: var(--snippet-background-color); + color: var(--snippet-text-color); + padding: 10px; + margin: 12px 0; + overflow: auto; + white-space: pre; +} +div.snippet-container { + position: relative; +} +@media screen and (max-width: 800px) { + pre.snippet { + padding-top: 26px; + } + button.snippet-copy { + top: 4px; + right: 4px; + } +} +pre.snippet .italic { + font-style: italic; +} +pre.snippet .bold { + font-weight: bold; +} +pre.snippet .highlighted { + background-color: var(--snippet-highlight-color); + border-radius: 10%; +} diff --git a/Documentation/JavaDoc/tag-search-index.js b/Documentation/JavaDoc/tag-search-index.js new file mode 100644 index 00000000..0367dae6 --- /dev/null +++ b/Documentation/JavaDoc/tag-search-index.js @@ -0,0 +1 @@ +tagSearchIndex = [];updateSearchResults(); \ No newline at end of file diff --git a/Documentation/JavaDoc/tpm/android/knox/java/CryptoManager.html b/Documentation/JavaDoc/tpm/android/knox/java/CryptoManager.html new file mode 100644 index 00000000..9a156b97 --- /dev/null +++ b/Documentation/JavaDoc/tpm/android/knox/java/CryptoManager.html @@ -0,0 +1,478 @@ + + + + +CryptoManager + + + + + + + + + + + + + + +
    + +
    +
    + +
    + +

    Class CryptoManager

    +
    +
    java.lang.Object +
    tpm.android.knox.java.CryptoManager
    +
    +
    +
    +
    public class CryptoManager +extends Object
    +
    This class provides all the methods we need for communication with the keystore and cryptographic systems. + It loads the keystore, generates and loads keys, encrypts and decrypts and signs and verifies.
    +
    +
    +
      + +
    • +
      +

      Constructor Summary

      +
      Constructors
      +
      +
      Constructor
      +
      Description
      + +
      +
      Constructs a new instance of CryptoManager with the default Android KeyStore.
      +
      +
      +
      +
    • + +
    • +
      +

      Method Summary

      +
      +
      +
      +
      +
      Modifier and Type
      +
      Method
      +
      Description
      +
      byte[]
      +
      decryptData(byte[] encryptedData)
      +
      +
      Decrypts the given encrypted data using a symmetric key stored in the Android KeyStore.
      +
      +
      byte[]
      +
      encryptData(byte[] data)
      +
      +
      Encrypts the given data using a symmetric key stored in the Android KeyStore.
      +
      +
      void
      +
      generateKeyPair(String key_id, + String keyGenInfo)
      +
      +
      Generates a new asymmetric key pair and saves it into the Android KeyStore.
      +
      +
      void
      +
      genKey(String key_id, + String keyGenInfo)
      +
      +
      Generates a new symmetric key and saves it into the Android KeyStore.
      +
      +
      void
      +
      loadKey(String key_id)
      +
      +
      Sets the `KEY_NAME` to the provided key identifier.
      +
      +
      byte[]
      +
      signData(byte[] data)
      +
      +
      Signs the given data using a private key stored in the Android KeyStore.
      +
      +
      boolean
      +
      verifySignature(byte[] data, + byte[] signedBytes)
      +
      +
      Verifies the given data against a signature produced by a private key stored in the Android KeyStore.
      +
      +
      +
      +
      +
      +

      Methods inherited from class java.lang.Object

      +clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      +
      +
    • +
    +
    +
    +
      + +
    • +
      +

      Constructor Details

      +
        +
      • +
        +

        CryptoManager

        +
        public CryptoManager() + throws KeyStoreException
        +
        Constructs a new instance of CryptoManager with the default Android KeyStore. +

        + This constructor initializes the CryptoManager with the default Android KeyStore. The Android KeyStore + provides a secure storage facility for cryptographic keys and certificates. Upon construction, the key store is + initialized, enabling the CryptoManager to interact with cryptographic keys securely stored on the + Android device. If the initialization of the key store fails, a KeyStoreException is thrown, indicating + issues with the key store setup process.

        +
        +
        Throws:
        +
        KeyStoreException - if the KeyStore Provider does not exist or fails to initialize, indicating issues with + the key store setup process.
        +
        +
        +
      • +
      +
      +
    • + +
    • +
      +

      Method Details

      + +
      +
    • +
    +
    + +
    +
    +
    + + diff --git a/Documentation/JavaDoc/tpm/android/knox/java/package-summary.html b/Documentation/JavaDoc/tpm/android/knox/java/package-summary.html new file mode 100644 index 00000000..182e54a7 --- /dev/null +++ b/Documentation/JavaDoc/tpm/android/knox/java/package-summary.html @@ -0,0 +1,92 @@ + + + + +tpm.android.knox.java + + + + + + + + + + + + + + +
    + +
    +
    +
    +

    Package tpm.android.knox.java

    +
    +
    +
    package tpm.android.knox.java
    +
    +
      +
    • +
      +
      Classes
      +
      +
      Class
      +
      Description
      + +
      +
      This class provides all the methods we need for communication with the keystore and cryptographic systems.
      +
      +
      +
      +
    • +
    +
    +
    +
    +
    + + diff --git a/Documentation/JavaDoc/tpm/android/knox/java/package-tree.html b/Documentation/JavaDoc/tpm/android/knox/java/package-tree.html new file mode 100644 index 00000000..476a077a --- /dev/null +++ b/Documentation/JavaDoc/tpm/android/knox/java/package-tree.html @@ -0,0 +1,66 @@ + + + + +tpm.android.knox.java Class Hierarchy + + + + + + + + + + + + + + +
    + +
    +
    +
    +

    Hierarchy For Package tpm.android.knox.java

    +
    +
    +

    Class Hierarchy

    + +
    +
    +
    +
    + + diff --git a/Documentation/JavaDoc/type-search-index.js b/Documentation/JavaDoc/type-search-index.js new file mode 100644 index 00000000..cd3053d9 --- /dev/null +++ b/Documentation/JavaDoc/type-search-index.js @@ -0,0 +1 @@ +typeSearchIndex = [{"l":"All Classes and Interfaces","u":"allclasses-index.html"},{"p":"tpm.android.knox.java","l":"CryptoManager"}];updateSearchResults(); \ No newline at end of file diff --git a/Documentation/Project_requirements.md b/Documentation/Project_requirements.md new file mode 100644 index 00000000..226eca66 --- /dev/null +++ b/Documentation/Project_requirements.md @@ -0,0 +1,30 @@ + +# Project requirements + +These are the requirements defined at the start of the project by Vulcan's Limes in collaboration with j&s-soft. They represent the original goals at the start of the project and are the foundation for all further development. Whether the requirements have been met is described below. + +## Functional requirements + + + +|Requirement | Status | Status explanation +|--|--|--| +| 1. Secure key management: The wrapper must be able to generate, store and manage keys securely using the HSM. | Complete | | +| 2. Integration with Samsung Knox Vault: The wrapper must enable the abstraction layer to use the functions of Knox Vault. | Partially complete | Key Usages are not implemented | +| 3. Access control: The wrapper must ensure that only a correctly authorized application can access the services of the wrapper. | Not verified | The planned pentest has not completed as of June 2024 | +| 4. Encryption and decryption: The wrapper must offer to encrypt and decrypt data using the keys stored in the HSM. | Partially complete | Asymmetric Encryption is not yet implemented +| 5. Logging and monitoring: The wrapper must provide a mechanism for logging of key operations and monitoring of access to keys stored in the Knox Vault in order to detect possible security breaches | Complete | Logging is provided by the abstraction layer + +## Non-functional requirements + +|Requirement | Status | Status explanation +|--|--|--| +| 1. Security: The wrapper must manage the keys securely. To check this requirement, j&s-soft carries out a pentest and incorporates the feedback into the wrapper. | Not verified | The planned pentest has not completed as of June 2024 | +| 2. Performance: The wrapper must be able to perform frequent operations such as data encryption and decryption in less than one second, provided that this is supported by the hardware security module. | not achievable | Encryption speed with AES-256 is about 0.1 mB/s +| 3. Reliability: The wrapper must provide a suitable response for correct requests and respond with an error message for incorrect requests. | Complete | +| 4. Compatibility: The wrapper must be compatible with all devices that currently support Knox Vault. A list of these devices can be found in the Documentation. Compliance with this requirement can only be checked for devices that are available to Vulcan's Limes. | Complete for S22 | Samsung S22 is the only device provided for testing +| 5. Integration with Samsung Knox SDK: The wrapper must be integrated with the Samsung Knox SDK in order to access and use the security functions and capabilities of Knox Vault. | Outdated | The wrapper is using the Android Keystore API to achieve this requirement +| 8. Implementation of the abstraction layer: The wrapper must enable all implementable functions of the abstraction layer | partially complete | Asymmetric Encryption and Key Usage are not implemented yet +| 9. Programming language: The wrapper is written in the Rust programming language. | Complete | +| 6. Maintainability: The code of the wrapper is documented so that any subsequent further development by other persons is possible. | Complete | +| 7. Documentation: Documentation is provided for the wrapper that describes installation, configuration and use. | Complete | diff --git a/Documentation/RustDoc/.lock b/Documentation/RustDoc/.lock new file mode 100644 index 00000000..e69de29b diff --git a/Documentation/RustDoc/crates.js b/Documentation/RustDoc/crates.js new file mode 100644 index 00000000..72bbdc9f --- /dev/null +++ b/Documentation/RustDoc/crates.js @@ -0,0 +1 @@ +window.ALL_CRATES = ["crypto_layer"]; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/all.html b/Documentation/RustDoc/crypto_layer/all.html new file mode 100644 index 00000000..3414167d --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/all.html @@ -0,0 +1,2 @@ +List of all items in this crate +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.AsymmetricEncryption.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.AsymmetricEncryption.html new file mode 100644 index 00000000..818690b1 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.AsymmetricEncryption.html @@ -0,0 +1,65 @@ +AsymmetricEncryption in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum AsymmetricEncryption { + Rsa(KeyBits), + Ecc(EccSchemeAlgorithm), +}
    Expand description

    Represents the available encryption algorithms.

    +

    This enum provides a C-compatible representation of different encryption +methods supported by the system, including asymmetric algorithms like RSA and ECC. +It is designed to be extensible, allowing for the addition +of more encryption algorithms in the future.

    +

    §Examples

    +

    Basic usage for RSA (assuming RsaBits is defined):

    + +
    use tpm_poc::common::crypto::algorithms::{KeyBits, encryption::AsymmetricEncryption};
    +
    +let encryption_method = AsymmetricEncryption::Rsa(KeyBits::Bits2048);
    +

    Basic usage for ECC:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::{AsymmetricEncryption, EccSchemeAlgorithm, EccCurves};
    +
    +let encryption_method = AsymmetricEncryption::Ecc(EccSchemeAlgorithm::EcDsa(EccCurves::Secp256k1));
    +

    §Note

    +

    This enum uses #[repr(C)] to ensure that it has the same memory layout as a C enum, +facilitating interfacing with C code or when ABI compatibility is required.

    +

    Variants§

    §

    Rsa(KeyBits)

    RSA encryption with selectable key sizes.

    +

    Allows specifying the key size for RSA encryption through the KeyBits enum, +supporting various standard key lengths for different security needs. RSA is widely used +for secure data transmission and is known for its simplicity and strong security properties, +provided a sufficiently large key size is used.

    +
    §

    Ecc(EccSchemeAlgorithm)

    Represents Elliptic Curve Cryptography (ECC) encryption.

    +

    ECC offers encryption methods based on elliptic curves over finite fields, +potentially including various algorithms and curves such as P-256, P-384, and others. +ECC is known for providing the same level of security as RSA but with smaller key sizes, +leading to faster computations and lower power consumption.

    +

    Implementations§

    source§

    impl AsymmetricEncryption

    source

    pub fn rsa_key_bits(&self) -> Option<KeyBits>

    Retrieves the RSA key size if the asymmetric encryption method is RSA.

    +
    §Returns
    +

    An Option<KeyBits> representing the key size of the RSA encryption. Returns None +if the encryption method is not RSA.

    +
    source

    pub fn ecc_scheme(&self) -> Option<EccSchemeAlgorithm>

    Retrieves the ECC scheme algorithm if the asymmetric encryption method is ECC.

    +

    This method extracts the specific ECC scheme algorithm used, such as ECDSA, ECDH, etc.

    +
    §Returns
    +

    An Option<EccSchemeAlgorithm> representing the ECC scheme. Returns None +if the encryption method is not ECC.

    +
    source

    pub fn ecc_curve(&self) -> Option<EccCurves>

    Retrieves the elliptic curve used if the asymmetric encryption method is ECC.

    +

    For ECC schemes that specify a curve, this method returns the curve being used. It supports +multiple ECC schemes and their associated curves.

    +
    §Returns
    +

    An Option<EccCurves> representing the elliptic curve used. Returns None +if the encryption method is not ECC or if the ECC scheme does not specify a curve.

    +

    Trait Implementations§

    source§

    impl Clone for AsymmetricEncryption

    source§

    fn clone(&self) -> AsymmetricEncryption

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for AsymmetricEncryption

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for AsymmetricEncryption

    source§

    fn default() -> Self

    Returns the “default value” for a type. Read more
    source§

    impl Copy for AsymmetricEncryption

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.BlockCiphers.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.BlockCiphers.html new file mode 100644 index 00000000..d0731be2 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.BlockCiphers.html @@ -0,0 +1,47 @@ +BlockCiphers in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum BlockCiphers { + Aes(SymmetricMode, KeyBits), + TripleDes(TripleDesNumKeys), + Des, + Rc2(Rc2KeyBits), + Camellia(SymmetricMode, KeyBits), +}
    Expand description

    Represents the available block cipher algorithms.

    +

    This enum provides a C-compatible representation of various block cipher algorithms supported, +including AES, Triple DES, DES, RC2, and Camellia. Each algorithm can be configured with specific modes of operation and key sizes. +It is designed for flexibility, allowing for easy extension to include additional block cipher algorithms.

    +

    §Examples

    +

    Using BlockCiphers with AES in CBC mode and a 256-bit key:

    + +
    use tpm_poc::common::crypto::algorithms::{KeyBits,encryption::{BlockCiphers, SymmetricMode}};
    +
    +let cipher = BlockCiphers::Aes(SymmetricMode::Cbc, KeyBits::Bits256);
    +

    Using BlockCiphers with Triple DES in EDE3 mode:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::{BlockCiphers, TripleDesNumKeys};
    +
    +let cipher = BlockCiphers::TripleDes(TripleDesNumKeys::Tdes3);
    +

    §Note

    +

    Marked with #[repr(C)] to ensure it has the same memory layout as a C enum, +facilitating ABI compatibility and interfacing with C code.

    +

    Variants§

    §

    Aes(SymmetricMode, KeyBits)

    AES (Advanced Encryption Standard) block cipher with selectable key sizes and modes.

    +
    §

    TripleDes(TripleDesNumKeys)

    Triple DES block cipher, either in two-key or three-key configurations.

    +
    §

    Des

    DES (Data Encryption Standard) block cipher, now considered insecure for many applications.

    +
    §

    Rc2(Rc2KeyBits)

    RC2 block cipher with selectable key sizes.

    +
    §

    Camellia(SymmetricMode, KeyBits)

    Camellia block cipher with selectable key sizes.

    +

    Trait Implementations§

    source§

    impl Clone for BlockCiphers

    source§

    fn clone(&self) -> BlockCiphers

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for BlockCiphers

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for BlockCiphers

    source§

    fn default() -> Self

    Returns the “default value” for a type. Read more
    source§

    impl Copy for BlockCiphers

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccCurves.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccCurves.html new file mode 100644 index 00000000..a7f5a4d7 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccCurves.html @@ -0,0 +1,59 @@ +EccCurves in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum EccCurves { + P256 = 0, + P384 = 1, + P521 = 2, + Secp256k1 = 3, + BrainpoolP256r1 = 4, + BrainpoolP384r1 = 5, + BrainpoolP512r1 = 6, + BrainpoolP638 = 7, + Curve25519 = 8, + Curve448 = 9, + Frp256v1 = 10, +}
    Expand description

    Specifies the curve types for Elliptic Curve Digital Signature Algorithm (ECDSA).

    +

    Lists the supported elliptic curve specifications for ECDSA, affecting security and performance. +Includes both NIST P-curves and others like secp256k1 and Brainpool curves.

    +

    §Examples

    +

    Selecting an ECDSA curve:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::EccCurves;
    +
    +let curve_type = EccCurves::Secp256k1;
    +

    §Note

    +

    Uses #[repr(C)] for C language compatibility.

    +

    Variants§

    §

    P256 = 0

    NIST P-256 curve.

    +
    §

    P384 = 1

    NIST P-384 curve.

    +
    §

    P521 = 2

    NIST P-521 curve.

    +
    §

    Secp256k1 = 3

    secp256k1 curve, commonly used in blockchain technologies.

    +
    §

    BrainpoolP256r1 = 4

    Brainpool P256r1 curve.

    +
    §

    BrainpoolP384r1 = 5

    Brainpool P384r1 curve.

    +
    §

    BrainpoolP512r1 = 6

    Brainpool P512r1 curve.

    +
    §

    BrainpoolP638 = 7

    Brainpool P638 curve.

    +
    §

    Curve25519 = 8

    Curve25519, popular for its security and performance.

    +
    §

    Curve448 = 9

    Curve448, known for high security and efficiency.

    +
    §

    Frp256v1 = 10

    FRP256v1, a French curve providing strong security and performance.

    +

    Trait Implementations§

    source§

    impl Clone for EccCurves

    source§

    fn clone(&self) -> EccCurves

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for EccCurves

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for EccCurves

    source§

    fn default() -> EccCurves

    Returns the “default value” for a type. Read more
    source§

    impl<'de> Deserialize<'de> for EccCurves

    source§

    fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
    where + __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    source§

    impl Hash for EccCurves

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for EccCurves

    source§

    fn eq(&self, other: &EccCurves) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Serialize for EccCurves

    source§

    fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
    where + __S: Serializer,

    Serialize this value into the given Serde serializer. Read more
    source§

    impl Copy for EccCurves

    source§

    impl Eq for EccCurves

    source§

    impl StructuralPartialEq for EccCurves

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    source§

    impl<T> DeserializeOwned for T
    where + T: for<'de> Deserialize<'de>,

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccSchemeAlgorithm.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccSchemeAlgorithm.html new file mode 100644 index 00000000..0181a10c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.EccSchemeAlgorithm.html @@ -0,0 +1,51 @@ +EccSchemeAlgorithm in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum EccSchemeAlgorithm { + EcDsa(EccCurves), + EcDh(EccCurves), + EcDaa(EccCurves), + Sm2(EccCurves), + EcSchnorr(EccCurves), + EcMqv(EccCurves), + Null, +}
    Expand description

    Enum representing the ECC scheme interface type.

    +

    Defines various algorithms that can be used in conjunction with Elliptic Curve Cryptography (ECC), +including signature schemes, key exchange protocols, and more. This allows for flexible cryptographic +configurations tailored to different security requirements and performance constraints.

    +

    §Examples

    +

    Selecting an ECC scheme:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::EccSchemeAlgorithm;
    +use tpm_poc::common::crypto::algorithms::encryption::EccCurves;
    +
    +let scheme = EccSchemeAlgorithm::EcDsa(EccCurves::Secp256k1);
    +

    Variants§

    §

    EcDsa(EccCurves)

    ECDSA: Elliptic Curve Digital Signature Algorithm.

    +
    §

    EcDh(EccCurves)

    ECDH: Elliptic Curve Diffie-Hellman for key agreement.

    +
    §

    EcDaa(EccCurves)

    ECDAA: Elliptic Curve Direct Anonymous Attestation.

    +
    §

    Sm2(EccCurves)

    SM2: A Chinese cryptographic standard for digital signatures and key exchange.

    +
    §

    EcSchnorr(EccCurves)

    EC-Schnorr: A Schnorr signature scheme variant using elliptic curves.

    +
    §

    EcMqv(EccCurves)

    ECMQV: Elliptic Curve Menezes-Qu-Vanstone, a key agreement scheme.

    +
    §

    Null

    Null: A placeholder or default value indicating no ECC scheme.

    +

    Trait Implementations§

    source§

    impl Clone for EccSchemeAlgorithm

    source§

    fn clone(&self) -> EccSchemeAlgorithm

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for EccSchemeAlgorithm

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for EccSchemeAlgorithm

    source§

    fn default() -> Self

    Returns the “default value” for a type. Read more
    source§

    impl<'de> Deserialize<'de> for EccSchemeAlgorithm

    source§

    fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
    where + __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    source§

    impl Hash for EccSchemeAlgorithm

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for EccSchemeAlgorithm

    source§

    fn eq(&self, other: &EccSchemeAlgorithm) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Serialize for EccSchemeAlgorithm

    source§

    fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
    where + __S: Serializer,

    Serialize this value into the given Serde serializer. Read more
    source§

    impl Copy for EccSchemeAlgorithm

    source§

    impl Eq for EccSchemeAlgorithm

    source§

    impl StructuralPartialEq for EccSchemeAlgorithm

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    source§

    impl<T> DeserializeOwned for T
    where + T: for<'de> Deserialize<'de>,

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.Rc2KeyBits.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.Rc2KeyBits.html new file mode 100644 index 00000000..896e9f38 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.Rc2KeyBits.html @@ -0,0 +1,36 @@ +Rc2KeyBits in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum Rc2KeyBits { + Rc2_40 = 0, + Rc2_64 = 1, + Rc2_128 = 2, +}
    Expand description

    Specifies the key sizes for the RC2 block cipher.

    +

    This enum lists the supported key sizes for RC2, such as 40, 64, and 128 bits. +The selection of key size impacts the security and compatibility of the encryption process.

    +

    §Examples

    +

    Selecting an RC2 key size of 128 bits:

    + +
    use tpm_poc::common::crypto::algorithms::encryption:: Rc2KeyBits;
    +
    +let key_size = Rc2KeyBits::Rc2_128;
    +

    §Note

    +

    Marked with #[repr(C)] to ensure compatibility with C-based environments.

    +

    Variants§

    §

    Rc2_40 = 0

    RC2 with a 40-bit key.

    +
    §

    Rc2_64 = 1

    RC2 with a 64-bit key.

    +
    §

    Rc2_128 = 2

    RC2 with a 128-bit key, offering the highest level of security among the options.

    +

    Trait Implementations§

    source§

    impl Clone for Rc2KeyBits

    source§

    fn clone(&self) -> Rc2KeyBits

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for Rc2KeyBits

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Copy for Rc2KeyBits

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.StreamCiphers.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.StreamCiphers.html new file mode 100644 index 00000000..1ae8ca0a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.StreamCiphers.html @@ -0,0 +1,41 @@ +StreamCiphers in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum StreamCiphers { + Rc4 = 0, + Chacha20 = 1, +}
    Expand description

    Represents the available stream cipher algorithms.

    +

    This enum provides a C-compatible representation of stream cipher algorithms such as RC4 and ChaCha20. +Stream ciphers encrypt plaintext one bit or byte at a time, offering different security and performance characteristics compared to block ciphers. +ChaCha20 is recommended for new applications due to its strong security profile.

    +

    §Examples

    +

    Using ChaCha20 stream cipher:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::StreamCiphers;
    +
    +let cipher = StreamCiphers::Chacha20;
    +

    §Note

    +

    #[repr(C)] attribute is used for C compatibility, important for interoperability with C-based systems.

    +

    Variants§

    §

    Rc4 = 0

    RC4 stream cipher.

    +

    Once widely used, RC4 is now considered insecure due to vulnerabilities that have +been discovered over time. It is included here for legacy support and should not +be used for new applications requiring secure encryption.

    +
    §

    Chacha20 = 1

    ChaCha20 stream cipher.

    +

    Provides strong security and high performance, making it suitable for a wide +range of modern applications. ChaCha20 is recommended for use when a secure and +efficient stream cipher is required.

    +

    Trait Implementations§

    source§

    impl Clone for StreamCiphers

    source§

    fn clone(&self) -> StreamCiphers

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.SymmetricMode.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.SymmetricMode.html new file mode 100644 index 00000000..e6e13f1a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.SymmetricMode.html @@ -0,0 +1,51 @@ +SymmetricMode in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum SymmetricMode { + Gcm = 0, + Ccm = 1, + Ecb = 2, + Cbc = 3, + Cfb = 4, + Ofb = 5, + Ctr = 6, +}
    Expand description

    Specifies the modes of operation for symmetric block ciphers.

    +

    This enum lists the supported modes of operation, such as GCM, CCM, ECB, CBC, CFB, OFB, and CTR. +These modes determine how block ciphers process plaintext and ciphertext, affecting security and performance characteristics.

    +

    §Examples

    +

    Selecting AES in GCM mode:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::SymmetricMode;
    +
    +let mode = SymmetricMode::Gcm;
    +

    §Note

    +

    #[repr(C)] attribute is used for C compatibility.

    +

    Variants§

    §

    Gcm = 0

    AES in Galois/Counter Mode (GCM) with selectable key sizes. +GCM is preferred for its performance and security, providing both encryption and authentication.

    +
    §

    Ccm = 1

    AES in Counter with CBC-MAC (CCM) mode with selectable key sizes. +CCM combines counter mode encryption with CBC-MAC authentication, suitable for constrained environments.

    +
    §

    Ecb = 2

    AES in Electronic Codebook (ECB) mode. +ECB encrypts each block of data independently. Due to its deterministic nature, it’s considered insecure for most uses.

    +
    §

    Cbc = 3

    AES in Cipher Block Chaining (CBC) mode. +CBC mode introduces dependencies between blocks for better security but requires proper IV management.

    +
    §

    Cfb = 4

    AES in Cipher Feedback (CFB) mode. +CFB mode turns AES into a stream cipher, allowing for encryption of partial blocks. It’s useful for streaming data.

    +
    §

    Ofb = 5

    AES in Output Feedback (OFB) mode. +OFB mode also converts AES into a stream cipher but generates keystream blocks independently of the plaintext.

    +
    §

    Ctr = 6

    AES in Counter (CTR) mode. +CTR mode encrypts a sequence of counters, offering high throughput and parallelization capabilities.

    +

    Trait Implementations§

    source§

    impl Clone for SymmetricMode

    source§

    fn clone(&self) -> SymmetricMode

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for SymmetricMode

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for SymmetricMode

    source§

    fn default() -> SymmetricMode

    Returns the “default value” for a type. Read more
    source§

    impl Copy for SymmetricMode

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.TripleDesNumKeys.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.TripleDesNumKeys.html new file mode 100644 index 00000000..af6dec96 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/enum.TripleDesNumKeys.html @@ -0,0 +1,34 @@ +TripleDesNumKeys in crypto_layer::common::crypto::algorithms::encryption - Rust +
    #[repr(C)]
    pub enum TripleDesNumKeys { + Tdes2 = 0, + Tdes3 = 1, +}
    Expand description

    Specifies the number of keys used in Triple DES configurations.

    +

    This enum provides options for two-key (Ede2) and three-key (Ede3) Triple DES configurations. +The choice between two-key and three-key configurations affects the security level and performance of the encryption process.

    +

    §Examples

    +

    Selecting a Triple DES configuration with three keys:

    + +
    use tpm_poc::common::crypto::algorithms::encryption::TripleDesNumKeys;
    +
    +let des_config = TripleDesNumKeys::Tdes3;
    +

    §Note

    +

    Uses #[repr(C)] for C language compatibility.

    +

    Variants§

    §

    Tdes2 = 0

    Two-key Triple DES, using two different keys for encryption.

    +
    §

    Tdes3 = 1

    Three-key Triple DES, providing enhanced security with three different keys.

    +

    Trait Implementations§

    source§

    impl Clone for TripleDesNumKeys

    source§

    fn clone(&self) -> TripleDesNumKeys

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for TripleDesNumKeys

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Copy for TripleDesNumKeys

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/index.html new file mode 100644 index 00000000..6a49417c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto::algorithms::encryption - Rust +

    Enums§

    • Represents the available encryption algorithms.
    • Represents the available block cipher algorithms.
    • Specifies the curve types for Elliptic Curve Digital Signature Algorithm (ECDSA).
    • Enum representing the ECC scheme interface type.
    • Specifies the key sizes for the RC2 block cipher.
    • Represents the available stream cipher algorithms.
    • Specifies the modes of operation for symmetric block ciphers.
    • Specifies the number of keys used in Triple DES configurations.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/sidebar-items.js new file mode 100644 index 00000000..0280fed5 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/encryption/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["AsymmetricEncryption","BlockCiphers","EccCurves","EccSchemeAlgorithm","Rc2KeyBits","StreamCiphers","SymmetricMode","TripleDesNumKeys"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/enum.KeyBits.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/enum.KeyBits.html new file mode 100644 index 00000000..c081f5a5 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/enum.KeyBits.html @@ -0,0 +1,44 @@ +KeyBits in crypto_layer::common::crypto::algorithms - Rust +
    #[repr(C)]
    pub enum KeyBits { + Bits128 = 0, + Bits192 = 1, + Bits256 = 2, + Bits512 = 3, + Bits1024 = 4, + Bits2048 = 5, + Bits3072 = 6, + Bits4096 = 7, + Bits8192 = 8, +}
    Expand description

    Represents the bit length of a cryptographic key.

    +

    This enum defines various key bit lengths commonly used in cryptography. +It provides a convenient way to specify and work with different key sizes.

    +

    The available key bit lengths are:

    +
      +
    • Bits128: 128-bit key length
    • +
    • Bits192: 192-bit key length
    • +
    • Bits256: 256-bit key length
    • +
    • Bits512: 512-bit key length
    • +
    • Bits1024: 1024-bit key length
    • +
    • Bits2048: 2048-bit key length
    • +
    • Bits3072: 3072-bit key length
    • +
    • Bits4096: 4096-bit key length
    • +
    • Bits8192: 8192-bit key length
    • +
    +

    This enum can be converted to and from u32 values using the From trait implementations.

    +

    Variants§

    §

    Bits128 = 0

    §

    Bits192 = 1

    §

    Bits256 = 2

    §

    Bits512 = 3

    §

    Bits1024 = 4

    §

    Bits2048 = 5

    §

    Bits3072 = 6

    §

    Bits4096 = 7

    §

    Bits8192 = 8

    Trait Implementations§

    source§

    impl Clone for KeyBits

    source§

    fn clone(&self) -> KeyBits

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for KeyBits

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl From<KeyBits> for u32

    source§

    fn from(value: KeyBits) -> Self

    Converts to this type from the input type.
    source§

    impl From<u32> for KeyBits

    source§

    fn from(value: u32) -> Self

    Converts to this type from the input type.
    source§

    impl Copy for KeyBits

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Hash.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Hash.html new file mode 100644 index 00000000..66fbbe22 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Hash.html @@ -0,0 +1,50 @@ +Hash in crypto_layer::common::crypto::algorithms::hashes - Rust +
    #[repr(C)]
    pub enum Hash { + Sha1, + Sha2(Sha2Bits), + Sha3(Sha3Bits), + Md2, + Md4, + Md5, + Ripemd160, +}
    Expand description

    Represents the available hashing algorithms.

    +

    This enum provides a C-compatible representation of various hashing algorithms, +including both historically significant and modern, secure algorithms.

    +

    When choosing a hashing algorithm, consider its security level and known vulnerabilities. +Algorithms like SHA-1, MD2, MD4, and MD5 are considered insecure for most cryptographic +purposes due to practical collision attacks and should be avoided for new applications. +Prefer using more secure algorithms like SHA-2 or SHA-3 for cryptographic purposes.

    +

    Variants§

    §

    Sha1

    SHA-1 hashing algorithm.

    +

    Considered insecure for most cryptographic purposes now due to vulnerabilities +that allow for practical collision attacks.

    +
    §

    Sha2(Sha2Bits)

    SHA-2 family of hashing algorithms with selectable digest sizes.

    +
    §

    Sha3(Sha3Bits)

    SHA-3 family of hashing algorithms, also known as Keccak, with selectable digest sizes.

    +
    §

    Md2

    MD2 hashing algorithm.

    +

    Considered cryptographically broken and unsuitable for further use due to significant +vulnerabilities.

    +
    §

    Md4

    MD4 hashing algorithm.

    +

    Faster but less secure than MD5; considered broken due to vulnerabilities to collision attacks.

    +
    §

    Md5

    MD5 hashing algorithm.

    +

    Widely used historically but can no longer be considered secure against collision attacks, +despite its continued use in non-cryptographic contexts like checksums.

    +
    §

    Ripemd160

    RIPEMD-160 hashing algorithm.

    +

    Designed to be a secure alternative to MD4 and MD5. It offers a good balance +of security for applications requiring a hash function more resilient to the +vulnerabilities affecting earlier Message Digest algorithms.

    +

    Trait Implementations§

    source§

    impl Clone for Hash

    source§

    fn clone(&self) -> Hash

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for Hash

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for Hash

    source§

    fn default() -> Self

    Returns the “default value” for a type. Read more
    source§

    impl Copy for Hash

    Auto Trait Implementations§

    §

    impl Freeze for Hash

    §

    impl RefUnwindSafe for Hash

    §

    impl Send for Hash

    §

    impl Sync for Hash

    §

    impl Unpin for Hash

    §

    impl UnwindSafe for Hash

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha2Bits.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha2Bits.html new file mode 100644 index 00000000..625e7ccd --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha2Bits.html @@ -0,0 +1,51 @@ +Sha2Bits in crypto_layer::common::crypto::algorithms::hashes - Rust +
    #[repr(C)]
    pub enum Sha2Bits { + Sha224 = 0, + Sha256 = 1, + Sha384 = 2, + Sha512 = 3, + Sha512_224 = 4, + Sha512_256 = 5, +}
    Expand description

    Specifies the digest sizes for the SHA-2 family of hashing algorithms.

    +

    This enum lists the supported digest sizes for SHA-2, providing a range of options +for different security and performance needs. The larger the digest size, the higher +the security level and collision resistance, but with a potential decrease in performance. +Selecting the appropriate digest size depends on the specific requirements of the application, +balancing security against computational overhead.

    +

    §Examples

    +

    Selecting a SHA-2 digest size:

    + +
    use tpm_poc::common::crypto::algorithms::hashes::Sha2Bits;
    +
    +let digest_size = Sha2Bits::Sha512;
    +

    §Note

    +

    #[repr(C)] attribute is used for C compatibility, facilitating interoperability with C-based systems.

    +

    Variants§

    §

    Sha224 = 0

    224-bit digest size.

    +
    §

    Sha256 = 1

    256-bit digest size, commonly used for its balance of security and performance.

    +
    §

    Sha384 = 2

    384-bit digest size.

    +
    §

    Sha512 = 3

    512-bit digest size, offering high security for sensitive applications.

    +
    §

    Sha512_224 = 4

    224-bit digest size variant of SHA-512, designed for compatibility with SHA-224.

    +
    §

    Sha512_256 = 5

    256-bit digest size variant of SHA-512, optimized for security and efficiency.

    +

    Trait Implementations§

    source§

    impl Clone for Sha2Bits

    source§

    fn clone(&self) -> Sha2Bits

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for Sha2Bits

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl From<Sha2Bits> for u32

    Implements the From trait to convert a Sha2Bits variant to its corresponding u32 value.

    +

    This can be useful when working with APIs or systems that expect digest sizes as integer values +instead of enum variants.

    +
    source§

    fn from(value: Sha2Bits) -> Self

    Converts to this type from the input type.
    source§

    impl From<u32> for Sha2Bits

    Implements the From trait to convert a u32 value to the corresponding Sha2Bits variant.

    +

    This allows for easy conversion from integer values to the enum variants, which can be useful +when working with external data sources or APIs that represent digest sizes as integers.

    +
    source§

    fn from(value: u32) -> Self

    Converts to this type from the input type.
    source§

    impl Copy for Sha2Bits

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha3Bits.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha3Bits.html new file mode 100644 index 00000000..40676eb8 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/enum.Sha3Bits.html @@ -0,0 +1,49 @@ +Sha3Bits in crypto_layer::common::crypto::algorithms::hashes - Rust +
    #[repr(C)]
    pub enum Sha3Bits { + Sha3_224 = 0, + Sha3_256 = 1, + Sha3_384 = 2, + Sha3_512 = 3, +}
    Expand description

    Specifies the digest sizes for the SHA-3 family of hashing algorithms.

    +

    SHA-3, also known as Keccak, offers a range of digest sizes to accommodate various +security levels and performance requirements. As a newer standard compared to SHA-2, +SHA-3 introduces a different cryptographic design that is resilient against many of the +vulnerabilities that affect older hashing algorithms. Choosing the correct digest size +allows developers to optimize for security and efficiency based on their specific needs. +A larger digest size generally provides higher security and collision resistance but may +come with a performance trade-off.

    +

    §Examples

    +

    Selecting a SHA-3 digest size:

    + +
    use tpm_poc::common::crypto::algorithms::hashes::Sha3Bits;
    +
    +let digest_size = Sha3Bits::Sha3_384;
    +

    §Note

    +

    Uses #[repr(C)] for C language compatibility, important for interoperability with C-based systems.

    +

    Variants§

    §

    Sha3_224 = 0

    224-bit digest size for SHA-3.

    +
    §

    Sha3_256 = 1

    256-bit digest size for SHA-3

    +
    §

    Sha3_384 = 2

    384-bit digest size for SHA-3

    +
    §

    Sha3_512 = 3

    512-bit digest size for SHA-3

    +

    Trait Implementations§

    source§

    impl Clone for Sha3Bits

    source§

    fn clone(&self) -> Sha3Bits

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for Sha3Bits

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl From<Sha3Bits> for u32

    Implements the From trait to convert a Sha3Bits variant to its corresponding u32 value.

    +

    This can be useful when working with APIs or systems that expect digest sizes as integer values +instead of enum variants.

    +
    source§

    fn from(value: Sha3Bits) -> Self

    Converts to this type from the input type.
    source§

    impl From<u32> for Sha3Bits

    Implements the From trait to convert a u32 value to the corresponding Sha3Bits variant.

    +

    This allows for easy conversion from integer values to the enum variants, which can be useful +when working with external data sources or APIs that represent digest sizes as integers.

    +
    source§

    fn from(value: u32) -> Self

    Converts to this type from the input type.
    source§

    impl Copy for Sha3Bits

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/index.html new file mode 100644 index 00000000..9cbc1076 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto::algorithms::hashes - Rust +

    Enums§

    • Represents the available hashing algorithms.
    • Specifies the digest sizes for the SHA-2 family of hashing algorithms.
    • Specifies the digest sizes for the SHA-3 family of hashing algorithms.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/sidebar-items.js new file mode 100644 index 00000000..5a1986e9 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/hashes/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Hash","Sha2Bits","Sha3Bits"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/index.html new file mode 100644 index 00000000..9424f815 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto::algorithms - Rust +

    Modules§

    Enums§

    • Represents the bit length of a cryptographic key.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/sidebar-items.js new file mode 100644 index 00000000..8ba744d9 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/algorithms/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["KeyBits"],"mod":["encryption","hashes"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/enum.KeyUsage.html b/Documentation/RustDoc/crypto_layer/common/crypto/enum.KeyUsage.html new file mode 100644 index 00000000..8b7743ef --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/enum.KeyUsage.html @@ -0,0 +1,27 @@ +KeyUsage in crypto_layer::common::crypto - Rust +
    #[repr(C)]
    pub enum KeyUsage { + ClientAuth = 0, + Decrypt = 1, + SignEncrypt = 2, + CreateX509 = 3, +}

    Variants§

    §

    ClientAuth = 0

    §

    Decrypt = 1

    §

    SignEncrypt = 2

    §

    CreateX509 = 3

    Trait Implementations§

    source§

    impl Clone for KeyUsage

    source§

    fn clone(&self) -> KeyUsage

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for KeyUsage

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Hash for KeyUsage

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for KeyUsage

    source§

    fn eq(&self, other: &KeyUsage) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Copy for KeyUsage

    source§

    impl Eq for KeyUsage

    source§

    impl StructuralPartialEq for KeyUsage

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/index.html new file mode 100644 index 00000000..5138561c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/index.html new file mode 100644 index 00000000..bbd6c763 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto::pkcs - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/sidebar-items.js new file mode 100644 index 00000000..1836c955 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["standards"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.ObjectIdentifiers.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.ObjectIdentifiers.html new file mode 100644 index 00000000..aeeb7ae6 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.ObjectIdentifiers.html @@ -0,0 +1,36 @@ +ObjectIdentifiers in crypto_layer::common::crypto::pkcs::standards - Rust +
    #[repr(C)]
    pub enum ObjectIdentifiers { + Oid(OidType), +}
    Expand description

    Represents the collection of Object Identifiers (OIDs) used in various cryptographic standards.

    +

    This enum provides a C-compatible representation of OIDs, which uniquely identify +algorithms and standards in cryptography. OIDs are used in multiple contexts, including +hashing algorithms, public key cryptography, encryption algorithms, key agreement protocols, +and certificate extensions.

    +

    §Examples

    +

    Using ObjectIdentifiers for RSA encryption:

    + +
    use tpm_poc::common::crypto::pkcs::standards::{ObjectIdentifiers, OidType};
    +
    +let oid = ObjectIdentifiers::Oid(OidType::RsaEncryption);
    +

    §Note

    +

    The #[repr(C)] attribute ensures C compatibility, facilitating the use of these enums +in systems where interoperability with C is required. OIDs play a crucial role in the +configuration and operation of cryptographic systems, ensuring the correct application +of algorithms and standards.

    +

    Variants§

    §

    Oid(OidType)

    Container for various cryptographic Object Identifiers (OIDs).

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.OidType.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.OidType.html new file mode 100644 index 00000000..7deef547 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.OidType.html @@ -0,0 +1,108 @@ +OidType in crypto_layer::common::crypto::pkcs::standards - Rust +
    #[repr(C)]
    pub enum OidType { +
    Show 48 variants Sha1WithRsaEncryption = 0, + Sha256WithRsaEncryption = 1, + Sha384WithRsaEncryption = 2, + Sha512WithRsaEncryption = 3, + IdSha1 = 4, + IdSha256 = 5, + IdSha384 = 6, + IdSha512 = 7, + RsaEncryption = 8, + IdRsaSsaPss = 9, + EcPublicKey = 10, + EcdsaWithSha1 = 11, + EcdsaWithSha256 = 12, + EcdsaWithSha384 = 13, + EcdsaWithSha512 = 14, + Aes128Cbc = 15, + Aes192Cbc = 16, + Aes256Cbc = 17, + Aes128Gcm = 18, + Aes192Gcm = 19, + Aes256Gcm = 20, + DhPublicNumber = 21, + EcdhStandardCurves = 22, + EcdhSpecifiedCurves = 23, + SubjectKeyIdentifier = 24, + KeyUsage = 25, + SubjectAltName = 26, + BasicConstraints = 27, + ExtendedKeyUsage = 28, + ServerAuth = 29, + ClientAuth = 30, + CodeSigning = 31, + EmailProtection = 32, + TimeStamping = 33, + OcspSigning = 34, + DocumentSigning = 35, + Pkix = 36, + Pkcs7Data = 37, + Pkcs7SignedData = 38, + Pkcs7EnvelopedData = 39, + Pkcs7SignedAndEnvelopedData = 40, + Pkcs7DigestData = 41, + Pkcs7EncryptedData = 42, + Pkcs9EmailAddress = 43, + Pkcs9UnstructuredName = 44, + Pkcs9ContentType = 45, + Pkcs9MessageDigest = 46, + Pkcs9SigningTime = 47, +
    }
    Expand description

    Enumerates specific Object Identifier (OID) types across cryptographic functionalities.

    +

    Lists OIDs for hashing algorithms, public key cryptography, encryption algorithms, +key agreement protocols, certificate extensions, extended key usage identifiers, and +other notable OIDs.

    +

    §Hashing Algorithms

    +
      +
    • Sha1WithRsaEncryption, Sha256WithRsaEncryption, etc.
    • +
    +

    §Public Key Cryptography

    +
      +
    • RsaEncryption, EcPublicKey, EcdsaWithSha*
    • +
    +

    §Encryption Algorithms

    +
      +
    • Aes128Cbc, Aes256Gcm, etc.
    • +
    +

    §Key Agreement

    +
      +
    • DhPublicNumber, EcdhStandardCurves
    • +
    +

    §Certificate Extensions

    +
      +
    • SubjectKeyIdentifier, ExtendedKeyUsage, etc.
    • +
    +

    §Extended Key Usage OIDs

    +
      +
    • ServerAuth, ClientAuth, CodeSigning, etc.
    • +
    +

    §Other notable OIDs

    +
      +
    • Pkix, Pkcs7Data, Pkcs9EmailAddress, etc.
    • +
    +

    §Examples

    +

    Selecting an OID for AES 256 CBC encryption:

    + +
    use tpm_poc::common::crypto::pkcs::standards::OidType;
    +
    +let oid_type = OidType::Aes256Cbc;
    +

    §Note

    +

    Uses #[repr(C)] for C language compatibility. Understanding and using the correct OIDs +is essential for ensuring cryptographic operations adhere to the intended standards and +protocols.

    +

    Variants§

    §

    Sha1WithRsaEncryption = 0

    §

    Sha256WithRsaEncryption = 1

    §

    Sha384WithRsaEncryption = 2

    §

    Sha512WithRsaEncryption = 3

    §

    IdSha1 = 4

    §

    IdSha256 = 5

    §

    IdSha384 = 6

    §

    IdSha512 = 7

    §

    RsaEncryption = 8

    §

    IdRsaSsaPss = 9

    §

    EcPublicKey = 10

    §

    EcdsaWithSha1 = 11

    §

    EcdsaWithSha256 = 12

    §

    EcdsaWithSha384 = 13

    §

    EcdsaWithSha512 = 14

    §

    Aes128Cbc = 15

    §

    Aes192Cbc = 16

    §

    Aes256Cbc = 17

    §

    Aes128Gcm = 18

    §

    Aes192Gcm = 19

    §

    Aes256Gcm = 20

    §

    DhPublicNumber = 21

    §

    EcdhStandardCurves = 22

    §

    EcdhSpecifiedCurves = 23

    §

    SubjectKeyIdentifier = 24

    §

    KeyUsage = 25

    §

    SubjectAltName = 26

    §

    BasicConstraints = 27

    §

    ExtendedKeyUsage = 28

    §

    ServerAuth = 29

    §

    ClientAuth = 30

    §

    CodeSigning = 31

    §

    EmailProtection = 32

    §

    TimeStamping = 33

    §

    OcspSigning = 34

    §

    DocumentSigning = 35

    §

    Pkix = 36

    §

    Pkcs7Data = 37

    §

    Pkcs7SignedData = 38

    §

    Pkcs7EnvelopedData = 39

    §

    Pkcs7SignedAndEnvelopedData = 40

    §

    Pkcs7DigestData = 41

    §

    Pkcs7EncryptedData = 42

    §

    Pkcs9EmailAddress = 43

    §

    Pkcs9UnstructuredName = 44

    §

    Pkcs9ContentType = 45

    §

    Pkcs9MessageDigest = 46

    §

    Pkcs9SigningTime = 47

    Implementations§

    source§

    impl OidType

    source

    pub fn as_str(&self) -> &'static str

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkcsType.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkcsType.html new file mode 100644 index 00000000..1b5e80ed --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkcsType.html @@ -0,0 +1,47 @@ +PkcsType in crypto_layer::common::crypto::pkcs::standards - Rust +
    #[repr(C)]
    pub enum PkcsType { + Pkcs1 = 0, + Pkcs3 = 1, + Pkcs5 = 2, + Pkcs7 = 3, + Pkcs8 = 4, + Pkcs9 = 5, + Pkcs10 = 6, + Pkcs11 = 7, + Pkcs12 = 8, +}
    Expand description

    Enumerates the PKCS (Public-Key Cryptography Standards) types.

    +

    Specifies the different PKCS standards, covering a wide array of cryptographic +functionalities, including key exchange, encryption, and digital signatures.

    +

    §Examples

    +

    Selecting a PKCS type for RSA cryptography:

    + +
    use tpm_poc::common::crypto::pkcs::standards::PkcsType;
    +
    +let pkcs_type = PkcsType::Pkcs1;
    +

    §Note

    +

    #[repr(C)] attribute for C compatibility.

    +

    Variants§

    §

    Pkcs1 = 0

    RSA Cryptography Standard.

    +
    §

    Pkcs3 = 1

    Diffie-Hellman Key Agreement Standard.

    +
    §

    Pkcs5 = 2

    Password-Based Cryptography Standard.

    +
    §

    Pkcs7 = 3

    Cryptographic Message Syntax Standard.

    +
    §

    Pkcs8 = 4

    Private-Key Information Syntax Standard.

    +
    §

    Pkcs9 = 5

    Selected Attribute Types.

    +
    §

    Pkcs10 = 6

    Certification Request Syntax Standard.

    +
    §

    Pkcs11 = 7

    Cryptographic Token Interface (Cryptoki).

    +
    §

    Pkcs12 = 8

    Personal Information Exchange Syntax Standard.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkiStandards.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkiStandards.html new file mode 100644 index 00000000..d0022b26 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.PkiStandards.html @@ -0,0 +1,45 @@ +PkiStandards in crypto_layer::common::crypto::pkcs::standards - Rust +
    #[repr(C)]
    pub enum PkiStandards { + Pkcs(PkcsType), + X509(X509Type), + Pem, +}
    Expand description

    Represents the various Public Key Infrastructure (PKI) standards.

    +

    This enum provides a C-compatible representation of different PKI standards, +including PKCS (Public-Key Cryptography Standards), X.509, and PEM (Privacy-Enhanced Mail). +These standards cover a wide range of purposes, from cryptographic keys and certificates +storage to secure communication protocols.

    +

    §Examples

    +

    Using PkiStandards with PKCS#1:

    + +
    use tpm_poc::common::crypto::pkcs::standards::{PkiStandards, PkcsType};
    +
    +let pki_standard = PkiStandards::Pkcs(PkcsType::Pkcs1);
    +

    Using PkiStandards with X.509 Certificates:

    + +
    use tpm_poc::common::crypto::pkcs::standards::{PkiStandards, X509Type};
    +
    +let pki_standard = PkiStandards::X509(X509Type::Certificate);
    +

    §Note

    +

    The #[repr(C)] attribute ensures C compatibility, making these enums suitable for +interfacing with C-based systems. They encompass a broad range of PKI applications, +from encryption and digital signatures to certificate management.

    +

    Variants§

    §

    Pkcs(PkcsType)

    PKCS (Public-Key Cryptography Standards) related operations.

    +

    Wraps various PKCS standards, each focusing on different aspects of public-key cryptography.

    +
    §

    X509(X509Type)

    X.509 related operations, including certificates and revocation lists.

    +
    §

    Pem

    PEM (Privacy-Enhanced Mail) format for storing and sending cryptographic keys and certificates.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.X509Type.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.X509Type.html new file mode 100644 index 00000000..79a32dd7 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/enum.X509Type.html @@ -0,0 +1,36 @@ +X509Type in crypto_layer::common::crypto::pkcs::standards - Rust +
    #[repr(C)]
    pub enum X509Type { + Certificate = 0, + CertificateRevocationList = 1, + CertificateSigningRequest = 2, +}
    Expand description

    Enumerates the types within the X.509 standard.

    +

    Specifies the different elements associated with X.509, a standard for creating +a public key infrastructure for digital certificates and public-key encryption.

    +

    §Examples

    +

    Selecting an X.509 type for certificates:

    + +
    use tpm_poc::common::crypto::pkcs::standards::X509Type;
    +
    +let x509_type = X509Type::Certificate;
    +

    §Note

    +

    Uses #[repr(C)] for compatibility with C language standards, facilitating use +in systems where interoperability with C is required.

    +

    Variants§

    §

    Certificate = 0

    Represents an X.509 certificate.

    +
    §

    CertificateRevocationList = 1

    Represents an X.509 Certificate Revocation List (CRL).

    +
    §

    CertificateSigningRequest = 2

    Represents an X.509 Certificate Signing Request (CSR).

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/index.html b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/index.html new file mode 100644 index 00000000..e4ae462b --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::crypto::pkcs::standards - Rust +

    Enums§

    • Represents the collection of Object Identifiers (OIDs) used in various cryptographic standards.
    • Enumerates specific Object Identifier (OID) types across cryptographic functionalities.
    • Enumerates the PKCS (Public-Key Cryptography Standards) types.
    • Represents the various Public Key Infrastructure (PKI) standards.
    • Enumerates the types within the X.509 standard.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/sidebar-items.js new file mode 100644 index 00000000..b5e88a6a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/pkcs/standards/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["ObjectIdentifiers","OidType","PkcsType","PkiStandards","X509Type"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/crypto/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/crypto/sidebar-items.js new file mode 100644 index 00000000..ce1d12e5 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/crypto/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["KeyUsage"],"mod":["algorithms","pkcs"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/error/enum.SecurityModuleError.html b/Documentation/RustDoc/crypto_layer/common/error/enum.SecurityModuleError.html new file mode 100644 index 00000000..c66dc41b --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/error/enum.SecurityModuleError.html @@ -0,0 +1,55 @@ +SecurityModuleError in crypto_layer::common::error - Rust +
    #[repr(C)]
    pub enum SecurityModuleError { + Tpm(TpmError), + SigningError(String), + DecryptionError(String), + EncryptionError(String), + SignatureVerificationError(String), + InitializationError(String), + CreationError(String), +}
    Expand description

    Represents errors that can occur within a security module.

    +

    This enum encapsulates various types of errors, including those originating +from a Hardware Security Module (HSM), a Trusted Platform Module (TPM), or during +the initialization process. It also includes errors related to cryptographic operations +such as signing, decryption, encryption, and signature verification.

    +

    Variants§

    §

    Tpm(TpmError)

    Error originating from a Trusted Platform Module (TPM).

    +
    §

    SigningError(String)

    Error that occurred during the signing operation.

    +

    This variant contains a descriptive error message.

    +
    §

    DecryptionError(String)

    Error that occurred during the decryption operation.

    +

    This variant contains a descriptive error message.

    +
    §

    EncryptionError(String)

    Error that occurred during the encryption operation.

    +

    This variant contains a descriptive error message.

    +
    §

    SignatureVerificationError(String)

    Error that occurred during the signature verification operation.

    +

    This variant contains a descriptive error message.

    +
    §

    InitializationError(String)

    Error that occurs during the initialization process.

    +

    This variant contains a descriptive error message.

    +
    §

    CreationError(String)

    Error that occurred during the key generation operation.

    +

    This variant contains a descriptive error message.

    +

    Trait Implementations§

    source§

    impl Debug for SecurityModuleError

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Display for SecurityModuleError

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Provides a human-readable description of the security module error.

    +

    Formats the error message based on the error type, ensuring that it is +descriptive and easy to understand.

    +
    source§

    impl Error for SecurityModuleError

    source§

    fn source(&self) -> Option<&(dyn Error + 'static)>

    Provides the source of the security module error, if available.

    +

    This method helps in understanding and diagnosing the underlying cause of the error, +particularly useful when debugging or logging error information.

    +

    For errors originating from an HSM or TPM, the source error is returned. +For other error variants, None is returned, as they do not have an underlying source error.

    +
    1.0.0 · source§

    fn description(&self) -> &str

    👎Deprecated since 1.42.0: use the Display impl or to_string()
    1.0.0 · source§

    fn cause(&self) -> Option<&dyn Error>

    👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
    source§

    fn provide<'a>(&'a self, request: &mut Request<'a>)

    🔬This is a nightly-only experimental API. (error_generic_member_access)
    Provides type based access to context intended for error reports. Read more
    source§

    impl From<TpmError> for SecurityModuleError

    source§

    fn from(err: TpmError) -> SecurityModuleError

    Converts a TpmError into a SecurityModuleError.

    +

    Similar to the conversion from HsmError, this allows for streamlined error +handling and propagation of TpmError values as SecurityModuleError.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToString for T
    where + T: Display + ?Sized,

    source§

    default fn to_string(&self) -> String

    Converts the given value to a String. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/error/index.html b/Documentation/RustDoc/crypto_layer/common/error/index.html new file mode 100644 index 00000000..5f6de975 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/error/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::error - Rust +

    Module crypto_layer::common::error

    source ·

    Enums§

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/error/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/error/sidebar-items.js new file mode 100644 index 00000000..25d10209 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["SecurityModuleError"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/factory/enum.SecurityModule.html b/Documentation/RustDoc/crypto_layer/common/factory/enum.SecurityModule.html new file mode 100644 index 00000000..6b437767 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/factory/enum.SecurityModule.html @@ -0,0 +1,30 @@ +SecurityModule in crypto_layer::common::factory - Rust +
    #[repr(C)]
    pub enum SecurityModule { + Tpm(TpmType), +}
    Expand description

    Represents the available types of security modules in the system.

    +

    This enum categorizes security modules into HSM (Hardware Security Module) and +TPM (Trusted Platform Module), allowing for a unified interface when working with different types of security modules.

    +

    Variants§

    Trait Implementations§

    source§

    impl Clone for SecurityModule

    source§

    fn clone(&self) -> SecurityModule

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for SecurityModule

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl From<&str> for SecurityModule

    Provides conversion from a string slice to a SecurityModule variant.

    +

    This implementation allows for easy instantiation of SecurityModule variants +from string identifiers, facilitating user or configuration-based module selection.

    +
    source§

    fn from(item: &str) -> Self

    Converts to this type from the input type.
    source§

    impl Hash for SecurityModule

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for SecurityModule

    source§

    fn eq(&self, other: &SecurityModule) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Eq for SecurityModule

    source§

    impl StructuralPartialEq for SecurityModule

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/factory/index.html b/Documentation/RustDoc/crypto_layer/common/factory/index.html new file mode 100644 index 00000000..4fa2593d --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/factory/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::factory - Rust +

    Structs§

    • A container struct for security module-related functionality.

    Enums§

    • Represents the available types of security modules in the system.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/factory/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/factory/sidebar-items.js new file mode 100644 index 00000000..7a7650a0 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/factory/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["SecurityModule"],"struct":["SecModules"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/factory/struct.SecModules.html b/Documentation/RustDoc/crypto_layer/common/factory/struct.SecModules.html new file mode 100644 index 00000000..8b54dcdf --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/factory/struct.SecModules.html @@ -0,0 +1,36 @@ +SecModules in crypto_layer::common::factory - Rust +
    #[repr(C)]
    pub struct SecModules {}
    Expand description

    A container struct for security module-related functionality.

    +

    This struct serves as a namespace for functions related to security module instances, +such as retrieving and creating them.

    +

    Implementations§

    source§

    impl SecModules

    Provides methods related to managing and accessing security module instances.

    +
    source

    pub fn get_instance( + key_id: String, + module: SecurityModule, + log: Option<Box<dyn LogConfig>> +) -> Option<Arc<Mutex<dyn Provider>>>

    Retrieves or creates an instance of a security module based on the provided key and type.

    +

    If an instance for the given module and key does not exist, it is created and stored. +Otherwise, the existing instance is returned.

    +
    §Arguments
    +
      +
    • key_id - A String identifier for the security module instance.
    • +
    • module - The SecurityModule variant representing the type of module to retrieve or create.
    • +
    +
    §Returns
    +

    An Option containing an Arc<Mutex<dyn Provider>> to the requested module instance, +or None if the module type is not supported or an error occurs during instance creation.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/index.html b/Documentation/RustDoc/crypto_layer/common/index.html new file mode 100644 index 00000000..44e416f2 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/index.html @@ -0,0 +1,2 @@ +crypto_layer::common - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/sidebar-items.js new file mode 100644 index 00000000..eac3d0ec --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["crypto","error","factory","traits"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/index.html b/Documentation/RustDoc/crypto_layer/common/traits/index.html new file mode 100644 index 00000000..c3205e6a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::traits - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/key_handle/index.html b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/index.html new file mode 100644 index 00000000..f4faf96e --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::traits::key_handle - Rust +

    Traits§

    • Defines a common interface for cryptographic key operations.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/key_handle/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/sidebar-items.js new file mode 100644 index 00000000..0d456acb --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["KeyHandle"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/key_handle/trait.KeyHandle.html b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/trait.KeyHandle.html new file mode 100644 index 00000000..5c46e374 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/key_handle/trait.KeyHandle.html @@ -0,0 +1,62 @@ +KeyHandle in crypto_layer::common::traits::key_handle - Rust +
    pub trait KeyHandle: Send + Sync + Debug {
    +    // Provided methods
    +    fn sign_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> { ... }
    +    fn decrypt_data(
    +        &self,
    +        _encrypted_data: &[u8]
    +    ) -> Result<Vec<u8>, SecurityModuleError> { ... }
    +    fn encrypt_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> { ... }
    +    fn verify_signature(
    +        &self,
    +        _data: &[u8],
    +        _signature: &[u8]
    +    ) -> Result<bool, SecurityModuleError> { ... }
    +}
    Expand description

    Defines a common interface for cryptographic key operations.

    +

    This trait specifies methods for key operations such as signing data, encrypting, +decrypting, and verifying signatures. It’s designed to be implemented by security +modules that manage cryptographic keys, ensuring a consistent interface for key +operations across different types of security modules. Implementors of this trait +must ensure thread safety.

    +

    Provided Methods§

    source

    fn sign_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError>

    Signs the given data using the cryptographic key.

    +
    §Arguments
    +
      +
    • data - A byte slice representing the data to be signed.
    • +
    +
    §Returns
    +

    A Result containing the signature as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source

    fn decrypt_data( + &self, + _encrypted_data: &[u8] +) -> Result<Vec<u8>, SecurityModuleError>

    Decrypts the given encrypted data using the cryptographic key.

    +
    §Arguments
    +
      +
    • encrypted_data - A byte slice representing the data to be decrypted.
    • +
    +
    §Returns
    +

    A Result containing the decrypted data as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source

    fn encrypt_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError>

    Encrypts the given data using the cryptographic key.

    +
    §Arguments
    +
      +
    • data - A byte slice representing the data to be encrypted.
    • +
    +
    §Returns
    +

    A Result containing the encrypted data as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source

    fn verify_signature( + &self, + _data: &[u8], + _signature: &[u8] +) -> Result<bool, SecurityModuleError>

    Verifies the signature of the given data using the cryptographic key.

    +
    §Arguments
    +
      +
    • data - A byte slice representing the data whose signature is to be verified.
    • +
    • signature - A byte slice representing the signature to be verified against the data.
    • +
    +
    §Returns
    +

    A Result containing a boolean indicating whether the signature is valid (true) or not (false), +or a SecurityModuleError on failure.

    +

    Implementors§

    source§

    impl KeyHandle for KnoxProvider

    Implements the Provider trait, providing cryptographic operations +such as signing, encryption, decryption, and signature verification for the TPM Knox Vault.

    +

    This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault

    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/log_config/index.html b/Documentation/RustDoc/crypto_layer/common/traits/log_config/index.html new file mode 100644 index 00000000..b319b013 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/log_config/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::traits::log_config - Rust +

    Traits§

    • Defines the interface for configuration data used by the Provider trait methods.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/log_config/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/traits/log_config/sidebar-items.js new file mode 100644 index 00000000..5983aa5d --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/log_config/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["LogConfig"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/log_config/trait.LogConfig.html b/Documentation/RustDoc/crypto_layer/common/traits/log_config/trait.LogConfig.html new file mode 100644 index 00000000..841de313 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/log_config/trait.LogConfig.html @@ -0,0 +1,14 @@ +LogConfig in crypto_layer::common::traits::log_config - Rust +
    pub trait LogConfig: Any + Debug {
    +    // Required method
    +    fn setup_logging(&self);
    +}
    Expand description

    Defines the interface for configuration data used by the Provider trait methods.

    +

    This trait allows for dynamic configuration structures to be passed to methods +like create_key and load_key. It enables the Provider implementations to +handle various types of configurations in a type-safe manner.

    +

    The Config trait ensures that configuration data can be dynamically cast to the +appropriate type needed by the Provider implementation. This is done through +the as_any method, which provides a way to perform dynamic downcasting.

    +

    Implementors of this trait must also implement the Debug trait to provide +debugging information and the Any trait to support type-safe downcasting.

    +

    Required Methods§

    Implementors§

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider/index.html b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/index.html new file mode 100644 index 00000000..5cdd814c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::traits::module_provider - Rust +

    Traits§

    • Defines the interface for a security module provider.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/sidebar-items.js new file mode 100644 index 00000000..18f47e14 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["Provider"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider/trait.Provider.html b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/trait.Provider.html new file mode 100644 index 00000000..3b9b334a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider/trait.Provider.html @@ -0,0 +1,63 @@ +Provider in crypto_layer::common::traits::module_provider - Rust +
    pub trait Provider: Send + Sync + KeyHandle + Debug {
    +    // Required methods
    +    fn create_key(
    +        &mut self,
    +        key_id: &str,
    +        config: Box<dyn Any>
    +    ) -> Result<(), SecurityModuleError>;
    +    fn load_key(
    +        &mut self,
    +        key_id: &str,
    +        config: Box<dyn Any>
    +    ) -> Result<(), SecurityModuleError>;
    +    fn initialize_module(&mut self) -> Result<(), SecurityModuleError>;
    +}
    Expand description

    Defines the interface for a security module provider.

    +

    This trait encapsulates operations related to cryptographic processing, such as +data encryption/decryption and signing/verification, as well as key management through +a ProviderHandle. It ensures a unified approach to interacting with different types +of security modules.

    +

    Implementors of this trait must also implement the KeyHandle trait to provide +cryptographic key operations.

    +

    Required Methods§

    source

    fn create_key( + &mut self, + key_id: &str, + config: Box<dyn Any> +) -> Result<(), SecurityModuleError>

    Creates a new cryptographic key identified by key_id.

    +
    §Arguments
    +
      +
    • key_id - A string slice that uniquely identifies the key to be created.
    • +
    • key_algorithm - The asymmetric encryption algorithm to be used for the key.
    • +
    • sym_algorithm - An optional symmetric encryption algorithm to be used with the key.
    • +
    • hash - An optional hash algorithm to be used with the key.
    • +
    • key_usages - A vector of AppKeyUsage values specifying the intended usages for the key.
    • +
    +
    §Returns
    +

    A Result that, on success, contains Ok(()), indicating that the key was created successfully. +On failure, it returns a SecurityModuleError.

    +
    source

    fn load_key( + &mut self, + key_id: &str, + config: Box<dyn Any> +) -> Result<(), SecurityModuleError>

    Loads an existing cryptographic key identified by key_id.

    +
    §Arguments
    +
      +
    • key_id - A string slice that uniquely identifies the key to be loaded.
    • +
    • key_algorithm - The asymmetric encryption algorithm used for the key.
    • +
    • sym_algorithm - An optional symmetric encryption algorithm used with the key.
    • +
    • hash - An optional hash algorithm used with the key.
    • +
    • key_usages - A vector of AppKeyUsage values specifying the intended usages for the key.
    • +
    +
    §Returns
    +

    A Result that, on success, contains Ok(()), indicating that the key was loaded successfully. +On failure, it returns a SecurityModuleError.

    +
    source

    fn initialize_module(&mut self) -> Result<(), SecurityModuleError>

    Initializes the security module and returns a handle for further operations.

    +

    This method should be called before performing any other operations with the security module. +It initializes the module and prepares it for use.

    +
    §Returns
    +

    A Result that, on success, contains Ok(()), indicating that the module was initialized successfully. +On failure, it returns a SecurityModuleError.

    +

    Implementors§

    source§

    impl Provider for KnoxProvider

    Implements the Provider trait, providing cryptographic operations utilizing a TPM.

    +

    This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault

    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/index.html b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/index.html new file mode 100644 index 00000000..8c5537aa --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/index.html @@ -0,0 +1,2 @@ +crypto_layer::common::traits::module_provider_config - Rust +

    Traits§

    • Defines the interface for configuration data used by the Provider trait methods.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/sidebar-items.js new file mode 100644 index 00000000..cf1e6d07 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["ProviderConfig"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.html b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.html new file mode 100644 index 00000000..e1055656 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.html @@ -0,0 +1,20 @@ +ProviderConfig in crypto_layer::common::traits::module_provider_config - Rust +
    pub trait ProviderConfig: Any + Debug {
    +    // Required method
    +    fn as_any(&self) -> &dyn Any;
    +}
    Expand description

    Defines the interface for configuration data used by the Provider trait methods.

    +

    This trait allows for dynamic configuration structures to be passed to methods +like create_key and load_key. It enables the Provider implementations to +handle various types of configurations in a type-safe manner.

    +

    The Config trait ensures that configuration data can be dynamically cast to the +appropriate type needed by the Provider implementation. This is done through +the as_any method, which provides a way to perform dynamic downcasting.

    +

    Implementors of this trait must also implement the Debug trait to provide +debugging information and the Any trait to support type-safe downcasting.

    +

    Required Methods§

    source

    fn as_any(&self) -> &dyn Any

    Returns a reference to the underlying Any type.

    +

    This method allows for downcasting the Config trait object to its concrete type.

    +
    §Returns
    +

    A reference to the Any trait object, which can then be downcast to the +specific type implementing Config.

    +

    Implementors§

    source§

    impl ProviderConfig for AndroidConfig

    source§

    impl ProviderConfig for KnoxConfig

    implements ProviderConfig for KnoxConfig

    +
    source§

    impl ProviderConfig for TpmConfig

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/common/traits/sidebar-items.js b/Documentation/RustDoc/crypto_layer/common/traits/sidebar-items.js new file mode 100644 index 00000000..47b661a4 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/common/traits/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["key_handle","log_config","module_provider","module_provider_config"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/index.html b/Documentation/RustDoc/crypto_layer/index.html new file mode 100644 index 00000000..be13b1b6 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/index.html @@ -0,0 +1,3 @@ +crypto_layer - Rust +

    Crate crypto_layer

    source ·

    Re-exports§

    Modules§

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/sidebar-items.js b/Documentation/RustDoc/crypto_layer/sidebar-items.js new file mode 100644 index 00000000..e37186e1 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["common","tpm"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/index.html new file mode 100644 index 00000000..3e9fdf12 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::android::android_logger - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/sidebar-items.js new file mode 100644 index 00000000..440c6455 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["DefaultAndroidLogger"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/struct.DefaultAndroidLogger.html b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/struct.DefaultAndroidLogger.html new file mode 100644 index 00000000..c8060673 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/android_logger/struct.DefaultAndroidLogger.html @@ -0,0 +1,17 @@ +DefaultAndroidLogger in crypto_layer::tpm::android::android_logger - Rust +
    pub struct DefaultAndroidLogger;

    Trait Implementations§

    source§

    impl Debug for DefaultAndroidLogger

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl LogConfig for DefaultAndroidLogger

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/config/enum.EncryptionMode.html b/Documentation/RustDoc/crypto_layer/tpm/android/config/enum.EncryptionMode.html new file mode 100644 index 00000000..3a1c248a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/config/enum.EncryptionMode.html @@ -0,0 +1,24 @@ +EncryptionMode in crypto_layer::tpm::android::config - Rust +
    pub enum EncryptionMode {
    +    Sym(BlockCiphers),
    +    ASym {
    +        algo: AsymmetricEncryption,
    +        digest: Hash,
    +    },
    +}

    Variants§

    Trait Implementations§

    source§

    impl Clone for EncryptionMode

    source§

    fn clone(&self) -> EncryptionMode

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for EncryptionMode

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Copy for EncryptionMode

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/config/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/config/index.html new file mode 100644 index 00000000..5c1b9bb6 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/config/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::android::config - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/config/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/config/sidebar-items.js new file mode 100644 index 00000000..be66e3bb --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/config/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["EncryptionMode"],"struct":["AndroidConfig"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/config/struct.AndroidConfig.html b/Documentation/RustDoc/crypto_layer/tpm/android/config/struct.AndroidConfig.html new file mode 100644 index 00000000..dc957186 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/config/struct.AndroidConfig.html @@ -0,0 +1,22 @@ +AndroidConfig in crypto_layer::tpm::android::config - Rust +
    pub struct AndroidConfig {
    +    pub mode: EncryptionMode,
    +    pub key_usages: Vec<KeyUsage>,
    +    pub hardware_backed: bool,
    +    pub vm: Option<JavaVM>,
    +}

    Fields§

    §mode: EncryptionMode§key_usages: Vec<KeyUsage>§hardware_backed: bool§vm: Option<JavaVM>

    Trait Implementations§

    source§

    impl Debug for AndroidConfig

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl ProviderConfig for AndroidConfig

    source§

    fn as_any(&self) -> &dyn Any

    Returns a reference to the underlying Any type. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/index.html new file mode 100644 index 00000000..65da06f4 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::android - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/knox/index.html new file mode 100644 index 00000000..ee25e4b0 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/index.html @@ -0,0 +1,8 @@ +crypto_layer::tpm::android::knox - Rust +

    Module crypto_layer::tpm::android::knox

    source ·

    Modules§

    Structs§

    • A struct defining the needed values for the create_key() and load_key() functions +At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both. +For hashing operations, SHA-256 is always used since it is the only one available on Knox Vault +The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI
    • A TPM-based cryptographic provider for managing cryptographic keys and performing +cryptographic operations in a Samsung environment. This provider uses the Java Native Interface +and the Android Keystore API to access the TPM “Knox Vault” developed by Samsung. In theory, +this code should also work for other TPMs on Android Devices, though it is only tested with Knox Vault
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/index.html new file mode 100644 index 00000000..5ed5a24d --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::android::knox::key_handle - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/sidebar-items.js new file mode 100644 index 00000000..5244ce01 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/key_handle/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/index.html b/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/index.html new file mode 100644 index 00000000..242b284f --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::android::knox::provider - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/sidebar-items.js new file mode 100644 index 00000000..5244ce01 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/provider/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/knox/sidebar-items.js new file mode 100644 index 00000000..aceb494c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["key_handle","provider"],"struct":["KnoxConfig","KnoxProvider"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxConfig.html b/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxConfig.html new file mode 100644 index 00000000..9f571b8d --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxConfig.html @@ -0,0 +1,36 @@ +KnoxConfig in crypto_layer::tpm::android::knox - Rust +
    pub struct KnoxConfig {
    +    pub key_algorithm: Option<AsymmetricEncryption>,
    +    pub sym_algorithm: Option<BlockCiphers>,
    +    pub vm: JavaVM,
    +}
    Expand description

    A struct defining the needed values for the create_key() and load_key() functions +At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both. +For hashing operations, SHA-256 is always used since it is the only one available on Knox Vault +The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI

    +

    Fields§

    §key_algorithm: Option<AsymmetricEncryption>§sym_algorithm: Option<BlockCiphers>§vm: JavaVM

    Implementations§

    source§

    impl KnoxConfig

    Implements KnoxConfig and provides a constructor

    +
    source

    pub fn new( + key_algorithm: Option<AsymmetricEncryption>, + sym_algorithm: Option<BlockCiphers>, + vm: JavaVM +) -> Result<KnoxConfig, SecurityModuleError>

    creates a new KnoxConfig +At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both. +Otherwise, load_key() or create_key() will return an Error. +The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI

    +

    Trait Implementations§

    source§

    impl Debug for KnoxConfig

    implements the debug trait for KnoxConfig for logging

    +
    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl ProviderConfig for KnoxConfig

    implements ProviderConfig for KnoxConfig

    +
    source§

    fn as_any(&self) -> &dyn Any

    Returns a reference to the underlying Any type. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxProvider.html b/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxProvider.html new file mode 100644 index 00000000..773e6943 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/knox/struct.KnoxProvider.html @@ -0,0 +1,119 @@ +KnoxProvider in crypto_layer::tpm::android::knox - Rust +
    #[repr(C)]
    pub struct KnoxProvider { /* private fields */ }
    Expand description

    A TPM-based cryptographic provider for managing cryptographic keys and performing +cryptographic operations in a Samsung environment. This provider uses the Java Native Interface +and the Android Keystore API to access the TPM “Knox Vault” developed by Samsung. In theory, +this code should also work for other TPMs on Android Devices, though it is only tested with Knox Vault

    +

    Implementations§

    source§

    impl KnoxProvider

    Provides functions to manage the KnoxProvider and the stored values within

    +
    source

    pub fn new() -> Self

    Constructs a new TpmProvider.

    +
    §Returns
    +

    A new empty instance of TpmProvider.

    +

    Trait Implementations§

    source§

    impl Debug for KnoxProvider

    implements the Debug trait for KnoxProvider to facilitate logging

    +
    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl KeyHandle for KnoxProvider

    Implements the Provider trait, providing cryptographic operations +such as signing, encryption, decryption, and signature verification for the TPM Knox Vault.

    +

    This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault

    +
    source§

    fn sign_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError>

    Signs data using the previously loaded cryptographic key.

    +

    This method hashes the input data using SHA-256 and then signs the hash. +The algorithm used for signing is determined by the currently loaded key. +If no key is loaded, an Error is returned.

    +
    §Arguments
    +
      +
    • data - The data to be signed.
    • +
    +
    §Returns
    +

    A Result containing the signature as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source§

    fn decrypt_data( + &self, + encrypted_data: &[u8] +) -> Result<Vec<u8>, SecurityModuleError>

    Decrypts the data with the currently loaded key. +The algorithm used for decryption is determined by the currently loaded key. +If no key is loaded, an Error is returned.

    +
    §Arguments
    +
      +
    • encrypted_data - The data to be decrypted.
    • +
    +
    §Returns
    +

    A Result containing the decrypted data as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source§

    fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError>

    Encrypts the data with the currently loaded key. +The algorithm used for Encryption is determined by the currently loaded key. +If no key is loaded, an Error is returned.

    +
    §Arguments
    +
      +
    • data - The data to be encrypted.
    • +
    +
    §Returns
    +

    A Result containing the encrypted data as a Vec<u8> on success, or a SecurityModuleError on failure.

    +
    source§

    fn verify_signature( + &self, + data: &[u8], + signature: &[u8] +) -> Result<bool, SecurityModuleError>

    Verifies a signature against the provided data.

    +

    This method hashes the input data using SHA-256 and then verifies the signature with the currently loaded key. +The algorithm used for verification is determined by the currently loaded key. +If no key is loaded, an Error is returned.

    +
    §Arguments
    +
      +
    • data - The original data associated with the signature.
    • +
    • signature - The signature to be verified.
    • +
    +
    §Returns
    +

    A Result indicating whether the signature is valid (true) or not (false), +or a SecurityModuleError on failure.

    +
    source§

    impl Provider for KnoxProvider

    Implements the Provider trait, providing cryptographic operations utilizing a TPM.

    +

    This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault

    +
    source§

    fn create_key( + &mut self, + key_id: &str, + config: Box<dyn Any> +) -> Result<(), SecurityModuleError>

    Creates a new cryptographic key identified by key_id.

    +

    This method creates a persistent cryptographic key using the specified algorithm +and identifier, making it retrievable for future operations. The key is created +and stored in Knox Vault. This method also loads the key for further usage, therefore it is +not necessary to load a key after creating it.

    +
    §Arguments
    +
      +
    • key_id - A string slice that uniquely identifies the key to be created.
    • +
    • Box<dyn Any- This box must contain a KnoxConfig, otherwise an Error is returned. +A KnoxConfig must contain the algorithm to be used as well as a reference to the JavaVM of the app +More details can be found in its documentation
    • +
    +
    §Returns
    +

    A Result that, on success, contains Ok(()), indicating that the key was created and stored successfully. +On failure, it returns a SecurityModuleError.

    +
    source§

    fn load_key( + &mut self, + key_id: &str, + config: Box<dyn Any> +) -> Result<(), SecurityModuleError>

    Loads an existing cryptographic key identified by key_id.

    +

    This method attempts to load a persisted cryptographic key by its identifier from the TPM. +If successful, it enables the key to be used for cryptographic operations.

    +
    §Arguments
    +
      +
    • key_id - A string slice that uniquely identifies the key to be loaded.
    • +
    • Box<dyn Any- This box must contain a KnoxConfig, otherwise an Error is returned. +A KnoxConfig must contain the algorithm to be used as well as a reference to the JavaVM of the app +More details can be found in its documentation
    • +
    +
    §Returns
    +

    A Result that, on success, contains Ok(()), indicating that the key was loaded successfully. +On failure, it returns a SecurityModuleError.

    +
    source§

    fn initialize_module(&mut self) -> Result<(), SecurityModuleError>

    This function ordinarily initialises the HSM. +For our implementation, this is not needed. You do not need to call this method, +and it will always return Ok(()) if you do.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/android/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/android/sidebar-items.js new file mode 100644 index 00000000..e0a10708 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/android/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["android_logger","config","knox"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/error/enum.TpmError.html b/Documentation/RustDoc/crypto_layer/tpm/core/error/enum.TpmError.html new file mode 100644 index 00000000..a571adae --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/error/enum.TpmError.html @@ -0,0 +1,41 @@ +TpmError in crypto_layer::tpm::core::error - Rust +
    #[repr(C)]
    pub enum TpmError { + Io(Error), + InitializationError(String), + UnsupportedOperation(String), + InternalError(Box<dyn Error>), +}
    Expand description

    Represents errors that can occur when interacting with a Trusted Platform Module (TPM).

    +

    This enum encapsulates different types of errors that may arise during TPM operations, +including I/O errors, Windows API errors, initialization errors, and unsupported operations. +It is designed to provide a clear and descriptive representation of the error, facilitating +error handling and logging.

    +

    Variants§

    §

    Io(Error)

    Error related to I/O operations, wrapping a std::io::Error.

    +
    §

    InitializationError(String)

    Error occurring during TPM initialization, containing an error message.

    +
    §

    UnsupportedOperation(String)

    Error indicating that an attempted operation is unsupported, containing a description.

    +
    §

    InternalError(Box<dyn Error>)

    Error indicating that an internal error occured, possibly caused by ffi bindings

    +

    Implementations§

    source§

    impl TpmError

    source

    pub fn description(&self) -> String

    Provides a human-readable description of the TPM error.

    +

    This implementation ensures that errors can be easily logged or displayed to the user, +with a clear indication of the error’s nature and origin.

    +

    Trait Implementations§

    source§

    impl Debug for TpmError

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Display for TpmError

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Error for TpmError

    Enables TpmError to be treated as a trait object for any error (dyn std::error::Error).

    +

    This implementation allows for compatibility with Rust’s standard error handling mechanisms, +facilitating the propagation and inspection of errors through the source method.

    +
    source§

    fn source(&self) -> Option<&(dyn Error + 'static)>

    The lower-level source of this error, if any. Read more
    1.0.0 · source§

    fn description(&self) -> &str

    👎Deprecated since 1.42.0: use the Display impl or to_string()
    1.0.0 · source§

    fn cause(&self) -> Option<&dyn Error>

    👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
    source§

    fn provide<'a>(&'a self, request: &mut Request<'a>)

    🔬This is a nightly-only experimental API. (error_generic_member_access)
    Provides type based access to context intended for error reports. Read more
    source§

    impl From<TpmError> for SecurityModuleError

    source§

    fn from(err: TpmError) -> SecurityModuleError

    Converts a TpmError into a SecurityModuleError.

    +

    Similar to the conversion from HsmError, this allows for streamlined error +handling and propagation of TpmError values as SecurityModuleError.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToString for T
    where + T: Display + ?Sized,

    source§

    default fn to_string(&self) -> String

    Converts the given value to a String. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/error/index.html b/Documentation/RustDoc/crypto_layer/tpm/core/error/index.html new file mode 100644 index 00000000..f8a6212c --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/error/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::core::error - Rust +

    Module crypto_layer::tpm::core::error

    source ·

    Enums§

    • Represents errors that can occur when interacting with a Trusted Platform Module (TPM).

    Traits§

    • A trait to allow ergonomic conversions to TpmError
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/error/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/core/error/sidebar-items.js new file mode 100644 index 00000000..0d2ff928 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["TpmError"],"trait":["ToTpmError"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/error/trait.ToTpmError.html b/Documentation/RustDoc/crypto_layer/tpm/core/error/trait.ToTpmError.html new file mode 100644 index 00000000..0d708ee4 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/error/trait.ToTpmError.html @@ -0,0 +1,12 @@ +ToTpmError in crypto_layer::tpm::core::error - Rust +
    pub trait ToTpmError<T> {
    +    // Required method
    +    fn err_internal(self) -> Result<T, TpmError>;
    +}
    Expand description

    A trait to allow ergonomic conversions to TpmError

    +

    Required Methods§

    source

    fn err_internal(self) -> Result<T, TpmError>

    Wrap any error in TpmError::InternalError +the wrapped error can be accessed througth the error trait

    +

    Implementations on Foreign Types§

    source§

    impl<T> ToTpmError<T> for Result<T>

    This allows converting the JNI result into a TpmError result.

    +
    source§

    fn err_internal(self) -> Result<T, TpmError>

    Converts the JNI result into a TpmError result. +If a Java exception was thrown, it retrieves the exception message and puts it into the error. +If no exception was thrown, it returns the JNI error as the TpmError.

    +

    Implementors§

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/index.html b/Documentation/RustDoc/crypto_layer/tpm/core/index.html new file mode 100644 index 00000000..47fa81c2 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::core - Rust +
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.AndroidTpmType.html b/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.AndroidTpmType.html new file mode 100644 index 00000000..bb8a72e3 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.AndroidTpmType.html @@ -0,0 +1,30 @@ +AndroidTpmType in crypto_layer::tpm::core::instance - Rust +
    #[repr(C)]
    pub enum AndroidTpmType { + Keystore = 0, + Knox = 1, +}
    Expand description

    Enumerates the types of TPM available on Android platforms.

    +

    Currently, this enum includes a single variant, Knox, which represents +Samsung’s Knox security platform that incorporates TPM functionalities.

    +

    Variants§

    §

    Keystore = 0

    Android Provider using the Android Keystore API

    +
    §

    Knox = 1

    Represents the Samsung Knox security platform with TPM functionalities.

    +

    Trait Implementations§

    source§

    impl Clone for AndroidTpmType

    source§

    fn clone(&self) -> AndroidTpmType

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for AndroidTpmType

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Hash for AndroidTpmType

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for AndroidTpmType

    source§

    fn eq(&self, other: &AndroidTpmType) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Eq for AndroidTpmType

    source§

    impl StructuralPartialEq for AndroidTpmType

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.TpmType.html b/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.TpmType.html new file mode 100644 index 00000000..d7273cf1 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/instance/enum.TpmType.html @@ -0,0 +1,37 @@ +TpmType in crypto_layer::tpm::core::instance - Rust +
    #[repr(C)]
    pub enum TpmType { + Android(AndroidTpmType), + None, +}
    Expand description

    Represents the different environments where a Trusted Platform Module (TPM) can operate.

    +

    This enum is designed to distinguish between various operating system environments, +including Windows, macOS, Linux, and Android-specific TPM types. It provides a unified +way to handle TPM operations across different platforms.

    +

    Variants§

    §

    Android(AndroidTpmType)

    Represents the TPM environment on Android platforms, with a specific AndroidTpmType.

    +
    §

    None

    Represents an unsupported or unknown TPM environment.

    +

    Trait Implementations§

    source§

    impl Clone for TpmType

    source§

    fn clone(&self) -> TpmType

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for TpmType

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for TpmType

    Provides a default TpmType based on the compile-time target operating system.

    +

    This implementation enables automatic selection of the TPM type most appropriate +for the current target OS, facilitating platform-agnostic TPM handling.

    +
    source§

    fn default() -> Self

    Returns the “default value” for a type. Read more
    source§

    impl From<&str> for TpmType

    Enables conversion from a string slice to a TpmType.

    +

    This implementation allows for dynamic TPM type determination based on string values, +useful for configuration or runtime environment specification.

    +
    source§

    fn from(s: &str) -> Self

    Converts to this type from the input type.
    source§

    impl Hash for TpmType

    source§

    fn hash<__H: Hasher>(&self, state: &mut __H)

    Feeds this value into the given Hasher. Read more
    1.3.0 · source§

    fn hash_slice<H>(data: &[Self], state: &mut H)
    where + H: Hasher, + Self: Sized,

    Feeds a slice of this type into the given Hasher. Read more
    source§

    impl PartialEq for TpmType

    source§

    fn eq(&self, other: &TpmType) -> bool

    This method tests for self and other values to be equal, and is used +by ==.
    1.0.0 · source§

    fn ne(&self, other: &Rhs) -> bool

    This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
    source§

    impl Eq for TpmType

    source§

    impl StructuralPartialEq for TpmType

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/instance/index.html b/Documentation/RustDoc/crypto_layer/tpm/core/instance/index.html new file mode 100644 index 00000000..df0bb90a --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/instance/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm::core::instance - Rust +

    Module crypto_layer::tpm::core::instance

    source ·

    Structs§

    • Manages instances of TPM providers based on the specified TpmType.

    Enums§

    • Enumerates the types of TPM available on Android platforms.
    • Represents the different environments where a Trusted Platform Module (TPM) can operate.
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/instance/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/core/instance/sidebar-items.js new file mode 100644 index 00000000..fbdf7d37 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/instance/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["AndroidTpmType","TpmType"],"struct":["TpmInstance"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/instance/struct.TpmInstance.html b/Documentation/RustDoc/crypto_layer/tpm/core/instance/struct.TpmInstance.html new file mode 100644 index 00000000..a6d8a8b9 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/instance/struct.TpmInstance.html @@ -0,0 +1,35 @@ +TpmInstance in crypto_layer::tpm::core::instance - Rust +
    #[repr(C)]
    pub struct TpmInstance { /* private fields */ }
    Expand description

    Manages instances of TPM providers based on the specified TpmType.

    +

    This structure is responsible for creating and encapsulating a TPM provider instance, +allowing for TPM operations such as key management and cryptographic functions +to be performed in a platform-specific manner.

    +

    Implementations§

    source§

    impl TpmInstance

    Facilitates the creation and management of TPM provider instances.

    +
    source

    pub fn create_instance( + key_id: String, + tpm_type: &TpmType +) -> Arc<Mutex<dyn Provider>>

    Creates a new TPM provider instance based on the specified TpmType.

    +

    This method abstracts over the differences between TPM implementations across +various platforms, providing a unified interface for TPM operations.

    +
    §Arguments
    +
      +
    • key_id - A unique identifier for the TPM key.
    • +
    • tpm_type - A reference to the TpmType indicating the environment of the TPM.
    • +
    +
    §Returns
    +

    An Arc<dyn Provider> encapsulating the created TPM provider instance.

    +

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/core/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/core/sidebar-items.js new file mode 100644 index 00000000..1fe60240 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/core/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["error","instance"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/index.html b/Documentation/RustDoc/crypto_layer/tpm/index.html new file mode 100644 index 00000000..f77176d8 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/index.html @@ -0,0 +1,2 @@ +crypto_layer::tpm - Rust +

    Module crypto_layer::tpm

    source ·

    Modules§

    Structs§

    \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/sidebar-items.js b/Documentation/RustDoc/crypto_layer/tpm/sidebar-items.js new file mode 100644 index 00000000..5adfb6d9 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["android","core"],"struct":["TpmConfig"]}; \ No newline at end of file diff --git a/Documentation/RustDoc/crypto_layer/tpm/struct.TpmConfig.html b/Documentation/RustDoc/crypto_layer/tpm/struct.TpmConfig.html new file mode 100644 index 00000000..25d88635 --- /dev/null +++ b/Documentation/RustDoc/crypto_layer/tpm/struct.TpmConfig.html @@ -0,0 +1,28 @@ +TpmConfig in crypto_layer::tpm - Rust +

    Struct crypto_layer::tpm::TpmConfig

    source ·
    pub struct TpmConfig {
    +    pub key_algorithm: AsymmetricEncryption,
    +    pub sym_algorithm: BlockCiphers,
    +    pub hash: Hash,
    +    pub key_usages: Vec<KeyUsage>,
    +}

    Fields§

    §key_algorithm: AsymmetricEncryption§sym_algorithm: BlockCiphers§hash: Hash§key_usages: Vec<KeyUsage>

    Implementations§

    source§

    impl TpmConfig

    source

    pub fn new( + key_algorithm: AsymmetricEncryption, + sym_algorithm: BlockCiphers, + hash: Hash, + key_usages: Vec<KeyUsage> +) -> Box<dyn ProviderConfig>

    Trait Implementations§

    source§

    impl Clone for TpmConfig

    source§

    fn clone(&self) -> TpmConfig

    Returns a copy of the value. Read more
    1.0.0 · source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    source§

    impl Debug for TpmConfig

    source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    source§

    impl Default for TpmConfig

    source§

    fn default() -> TpmConfig

    Returns the “default value” for a type. Read more
    source§

    impl ProviderConfig for TpmConfig

    source§

    fn as_any(&self) -> &dyn Any

    Returns a reference to the underlying Any type. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    source§

    impl<T> Any for T
    where + T: 'static + ?Sized,

    source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    source§

    impl<T> Borrow<T> for T
    where + T: ?Sized,

    source§

    fn borrow(&self) -> &T

    Immutably borrows from an owned value. Read more
    source§

    impl<T> BorrowMut<T> for T
    where + T: ?Sized,

    source§

    fn borrow_mut(&mut self) -> &mut T

    Mutably borrows from an owned value. Read more
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    §

    impl<'a, T> Desc<'a, T> for T

    §

    fn lookup(self, _: &JNIEnv<'a>) -> Result<T, Error>

    Look up the concrete type from the JVM.
    source§

    impl<T> From<T> for T

    source§

    fn from(t: T) -> T

    Returns the argument unchanged.

    +
    §

    impl<T> Instrument for T

    §

    fn instrument(self, span: Span) -> Instrumented<Self>

    Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
    §

    fn in_current_span(self) -> Instrumented<Self>

    Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
    source§

    impl<T, U> Into<U> for T
    where + U: From<T>,

    source§

    fn into(self) -> U

    Calls U::from(self).

    +

    That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

    +
    source§

    impl<T> ToOwned for T
    where + T: Clone,

    §

    type Owned = T

    The resulting type after obtaining ownership.
    source§

    fn to_owned(&self) -> T

    Creates owned data from borrowed data, usually by cloning. Read more
    source§

    fn clone_into(&self, target: &mut T)

    Uses borrowed data to replace owned data, usually by cloning. Read more
    source§

    impl<T, U> TryFrom<U> for T
    where + U: Into<T>,

    §

    type Error = Infallible

    The type returned in the event of a conversion error.
    source§

    fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

    Performs the conversion.
    source§

    impl<T, U> TryInto<U> for T
    where + U: TryFrom<T>,

    §

    type Error = <U as TryFrom<T>>::Error

    The type returned in the event of a conversion error.
    source§

    fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

    Performs the conversion.
    §

    impl<T> WithSubscriber for T

    §

    fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
    where + S: Into<Dispatch>,

    Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    §

    fn with_current_subscriber(self) -> WithDispatch<Self>

    Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
    \ No newline at end of file diff --git a/Documentation/RustDoc/help.html b/Documentation/RustDoc/help.html new file mode 100644 index 00000000..8a99348f --- /dev/null +++ b/Documentation/RustDoc/help.html @@ -0,0 +1,2 @@ +Help +

    Rustdoc help

    Back
    \ No newline at end of file diff --git a/Documentation/RustDoc/search-index.js b/Documentation/RustDoc/search-index.js new file mode 100644 index 00000000..b4ee3115 --- /dev/null +++ b/Documentation/RustDoc/search-index.js @@ -0,0 +1,5 @@ +var searchIndex = new Map(JSON.parse('[\ +["crypto_layer",{"doc":"","t":"EECCCCCCPPPGPCNNNNNNNNNNNCNNNNPPPPPPPPPGNNNNCNNNCNNNNNNNPGGPPPPPPPPPPPPPPPPPPPPGGPPPPPPPPGPPPPPPPGGPPPGNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGPPPPPPPPGPPGPPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCPPPPPPPPPPPPPPPPPPPPPPPPPPPPPGPPGPPPPPPPPPPPPPPPPPPPPPPGGPPPPPPPPPPPGNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNPPPPGPPPNNNNNNNNNNNNNNFGPNNNNNNNNNNNNNNNNNNNNNNNNNNCCCCKNNNNKMKMMMKMFCNNNNNCNNNONOONNNONNNNCCCFNNNNNNNNNNNPFGPNNNNNNNNNNNONNONNNNONNNNNNNOOOFFNNNNNNNNNNNNNNNOCNNNNNNNCNONNNNNNNOCCPPPKGPNNNMNNNNNNNNNNNPGPPPFGNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["SecModules","SecurityModuleError","common","tpm","crypto","error","factory","traits","ClientAuth","CreateX509","Decrypt","KeyUsage","SignEncrypt","algorithms","borrow","borrow_mut","clone","clone_into","eq","fmt","from","hash","into","lookup","lookup","pkcs","to_owned","try_from","try_into","type_id","Bits1024","Bits128","Bits192","Bits2048","Bits256","Bits3072","Bits4096","Bits512","Bits8192","KeyBits","borrow","borrow_mut","clone","clone_into","encryption","fmt","from","from","hashes","into","lookup","lookup","to_owned","try_from","try_into","type_id","Aes","AsymmetricEncryption","BlockCiphers","BrainpoolP256r1","BrainpoolP384r1","BrainpoolP512r1","BrainpoolP638","Camellia","Cbc","Ccm","Cfb","Chacha20","Ctr","Curve25519","Curve448","Des","EcDaa","EcDh","EcDsa","EcMqv","EcSchnorr","Ecb","Ecc","EccCurves","EccSchemeAlgorithm","Frp256v1","Gcm","Null","Ofb","P256","P384","P521","Rc2","Rc2KeyBits","Rc2_128","Rc2_40","Rc2_64","Rc4","Rsa","Secp256k1","Sm2","StreamCiphers","SymmetricMode","Tdes2","Tdes3","TripleDes","TripleDesNumKeys","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","default","default","default","default","default","deserialize","deserialize","ecc_curve","ecc_scheme","eq","eq","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","hash","hash","into","into","into","into","into","into","into","into","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","rsa_key_bits","serialize","serialize","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","Hash","Md2","Md4","Md5","Ripemd160","Sha1","Sha2","Sha224","Sha256","Sha2Bits","Sha3","Sha384","Sha3Bits","Sha3_224","Sha3_256","Sha3_384","Sha3_512","Sha512","Sha512_224","Sha512_256","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone_into","clone_into","clone_into","default","fmt","fmt","fmt","from","from","from","from","from","into","into","into","lookup","lookup","lookup","lookup","lookup","lookup","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","standards","Aes128Cbc","Aes128Gcm","Aes192Cbc","Aes192Gcm","Aes256Cbc","Aes256Gcm","BasicConstraints","Certificate","CertificateRevocationList","CertificateSigningRequest","ClientAuth","CodeSigning","DhPublicNumber","DocumentSigning","EcPublicKey","EcdhSpecifiedCurves","EcdhStandardCurves","EcdsaWithSha1","EcdsaWithSha256","EcdsaWithSha384","EcdsaWithSha512","EmailProtection","ExtendedKeyUsage","IdRsaSsaPss","IdSha1","IdSha256","IdSha384","IdSha512","KeyUsage","ObjectIdentifiers","OcspSigning","Oid","OidType","Pem","Pkcs","Pkcs1","Pkcs10","Pkcs11","Pkcs12","Pkcs3","Pkcs5","Pkcs7","Pkcs7Data","Pkcs7DigestData","Pkcs7EncryptedData","Pkcs7EnvelopedData","Pkcs7SignedAndEnvelopedData","Pkcs7SignedData","Pkcs8","Pkcs9","Pkcs9ContentType","Pkcs9EmailAddress","Pkcs9MessageDigest","Pkcs9SigningTime","Pkcs9UnstructuredName","PkcsType","PkiStandards","Pkix","RsaEncryption","ServerAuth","Sha1WithRsaEncryption","Sha256WithRsaEncryption","Sha384WithRsaEncryption","Sha512WithRsaEncryption","SubjectAltName","SubjectKeyIdentifier","TimeStamping","X509","X509Type","as_str","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","from","from","from","from","from","into","into","into","into","into","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","lookup","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","CreationError","DecryptionError","EncryptionError","InitializationError","SecurityModuleError","SignatureVerificationError","SigningError","Tpm","borrow","borrow_mut","fmt","fmt","from","from","into","lookup","lookup","source","to_string","try_from","try_into","type_id","SecModules","SecurityModule","Tpm","borrow","borrow","borrow_mut","borrow_mut","clone","clone_into","eq","fmt","from","from","from","get_instance","hash","into","into","lookup","lookup","lookup","lookup","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","key_handle","log_config","module_provider","module_provider_config","KeyHandle","decrypt_data","encrypt_data","sign_data","verify_signature","LogConfig","setup_logging","Provider","create_key","initialize_module","load_key","ProviderConfig","as_any","TpmConfig","android","as_any","borrow","borrow_mut","clone","clone_into","core","default","fmt","from","hash","into","key_algorithm","key_usages","lookup","lookup","new","sym_algorithm","to_owned","try_from","try_into","type_id","android_logger","config","knox","DefaultAndroidLogger","borrow","borrow_mut","fmt","from","into","lookup","lookup","setup_logging","try_from","try_into","type_id","ASym","AndroidConfig","EncryptionMode","Sym","as_any","borrow","borrow","borrow_mut","borrow_mut","clone","clone_into","fmt","fmt","from","from","hardware_backed","into","into","key_usages","lookup","lookup","lookup","lookup","mode","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","vm","algo","digest","KnoxConfig","KnoxProvider","as_any","borrow","borrow","borrow_mut","borrow_mut","create_key","decrypt_data","encrypt_data","fmt","fmt","from","from","initialize_module","into","into","key_algorithm","key_handle","load_key","lookup","lookup","lookup","lookup","new","new","provider","sign_data","sym_algorithm","try_from","try_from","try_into","try_into","type_id","type_id","verify_signature","vm","error","instance","InitializationError","InternalError","Io","ToTpmError","TpmError","UnsupportedOperation","borrow","borrow_mut","description","err_internal","fmt","fmt","from","into","lookup","lookup","source","to_string","try_from","try_into","type_id","Android","AndroidTpmType","Keystore","Knox","None","TpmInstance","TpmType","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","create_instance","default","eq","eq","fmt","fmt","from","from","from","from","hash","hash","into","into","into","lookup","lookup","lookup","lookup","lookup","lookup","to_owned","to_owned","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id"],"q":[[0,"crypto_layer"],[4,"crypto_layer::common"],[8,"crypto_layer::common::crypto"],[30,"crypto_layer::common::crypto::algorithms"],[56,"crypto_layer::common::crypto::algorithms::encryption"],[222,"crypto_layer::common::crypto::algorithms::hashes"],[284,"crypto_layer::common::crypto::pkcs"],[285,"crypto_layer::common::crypto::pkcs::standards"],[400,"crypto_layer::common::error"],[422,"crypto_layer::common::factory"],[451,"crypto_layer::common::traits"],[455,"crypto_layer::common::traits::key_handle"],[460,"crypto_layer::common::traits::log_config"],[462,"crypto_layer::common::traits::module_provider"],[466,"crypto_layer::common::traits::module_provider_config"],[468,"crypto_layer::tpm"],[491,"crypto_layer::tpm::android"],[494,"crypto_layer::tpm::android::android_logger"],[506,"crypto_layer::tpm::android::config"],[538,"crypto_layer::tpm::android::config::EncryptionMode"],[540,"crypto_layer::tpm::android::knox"],[577,"crypto_layer::tpm::core"],[579,"crypto_layer::tpm::core::error"],[600,"crypto_layer::tpm::core::instance"],[649,"core::fmt"],[650,"core::fmt"],[651,"jni::wrapper::jnienv"],[652,"jni::wrapper::errors"],[653,"core::result"],[654,"jni::wrapper::jnienv"],[655,"serde::de"],[656,"core::option"],[657,"serde::ser"],[658,"core::error"],[659,"alloc::string"],[660,"alloc::boxed"],[661,"std::sync::mutex"],[662,"alloc::sync"],[663,"alloc::vec"],[664,"core::any"]],"d":["","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","Calls U::from(self).","","","","","","","","","","","","","","","","","Represents the bit length of a cryptographic key.","","","","","","","Returns the argument unchanged.","","","Calls U::from(self).","","","","","","","AES (Advanced Encryption Standard) block cipher with …","Represents the available encryption algorithms.","Represents the available block cipher algorithms.","Brainpool P256r1 curve.","Brainpool P384r1 curve.","Brainpool P512r1 curve.","Brainpool P638 curve.","Camellia block cipher with selectable key sizes.","AES in Cipher Block Chaining (CBC) mode. CBC mode …","AES in Counter with CBC-MAC (CCM) mode with selectable key …","AES in Cipher Feedback (CFB) mode. CFB mode turns AES into …","ChaCha20 stream cipher.","AES in Counter (CTR) mode. CTR mode encrypts a sequence of …","Curve25519, popular for its security and performance.","Curve448, known for high security and efficiency.","DES (Data Encryption Standard) block cipher, now …","ECDAA: Elliptic Curve Direct Anonymous Attestation.","ECDH: Elliptic Curve Diffie-Hellman for key agreement.","ECDSA: Elliptic Curve Digital Signature Algorithm.","ECMQV: Elliptic Curve Menezes-Qu-Vanstone, a key agreement …","EC-Schnorr: A Schnorr signature scheme variant using …","AES in Electronic Codebook (ECB) mode. ECB encrypts each …","Represents Elliptic Curve Cryptography (ECC) encryption.","Specifies the curve types for Elliptic Curve Digital …","Enum representing the ECC scheme interface type.","FRP256v1, a French curve providing strong security and …","AES in Galois/Counter Mode (GCM) with selectable key sizes.","Null: A placeholder or default value indicating no ECC …","AES in Output Feedback (OFB) mode. OFB mode also converts …","NIST P-256 curve.","NIST P-384 curve.","NIST P-521 curve.","RC2 block cipher with selectable key sizes.","Specifies the key sizes for the RC2 block cipher.","RC2 with a 128-bit key, offering the highest level of …","RC2 with a 40-bit key.","RC2 with a 64-bit key.","RC4 stream cipher.","RSA encryption with selectable key sizes.","secp256k1 curve, commonly used in blockchain technologies.","SM2: A Chinese cryptographic standard for digital …","Represents the available stream cipher algorithms.","Specifies the modes of operation for symmetric block …","Two-key Triple DES, using two different keys for …","Three-key Triple DES, providing enhanced security with …","Triple DES block cipher, either in two-key or three-key …","Specifies the number of keys used in Triple DES …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Retrieves the elliptic curve used if the asymmetric …","Retrieves the ECC scheme algorithm if the asymmetric …","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","Retrieves the RSA key size if the asymmetric encryption …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Represents the available hashing algorithms.","MD2 hashing algorithm.","MD4 hashing algorithm.","MD5 hashing algorithm.","RIPEMD-160 hashing algorithm.","SHA-1 hashing algorithm.","SHA-2 family of hashing algorithms with selectable digest …","224-bit digest size.","256-bit digest size, commonly used for its balance of …","Specifies the digest sizes for the SHA-2 family of hashing …","SHA-3 family of hashing algorithms, also known as Keccak, …","384-bit digest size.","Specifies the digest sizes for the SHA-3 family of hashing …","224-bit digest size for SHA-3.","256-bit digest size for SHA-3","384-bit digest size for SHA-3","512-bit digest size for SHA-3","512-bit digest size, offering high security for sensitive …","224-bit digest size variant of SHA-512, designed for …","256-bit digest size variant of SHA-512, optimized for …","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","","","","","","","","Represents an X.509 certificate.","Represents an X.509 Certificate Revocation List (CRL).","Represents an X.509 Certificate Signing Request (CSR).","","","","","","","","","","","","","","","","","","","","Represents the collection of Object Identifiers (OIDs) …","","Container for various cryptographic Object Identifiers …","Enumerates specific Object Identifier (OID) types across …","PEM (Privacy-Enhanced Mail) format for storing and sending …","PKCS (Public-Key Cryptography Standards) related …","RSA Cryptography Standard.","Certification Request Syntax Standard.","Cryptographic Token Interface (Cryptoki).","Personal Information Exchange Syntax Standard.","Diffie-Hellman Key Agreement Standard.","Password-Based Cryptography Standard.","Cryptographic Message Syntax Standard.","","","","","","","Private-Key Information Syntax Standard.","Selected Attribute Types.","","","","","","Enumerates the PKCS (Public-Key Cryptography Standards) …","Represents the various Public Key Infrastructure (PKI) …","","","","","","","","","","","X.509 related operations, including certificates and …","Enumerates the types within the X.509 standard.","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","","","","","","","Error that occurred during the key generation operation.","Error that occurred during the decryption operation.","Error that occurred during the encryption operation.","Error that occurs during the initialization process.","Represents errors that can occur within a security module.","Error that occurred during the signature verification …","Error that occurred during the signing operation.","Error originating from a Trusted Platform Module (TPM).","","","","Provides a human-readable description of the security …","Returns the argument unchanged.","Converts a TpmError into a SecurityModuleError.","Calls U::from(self).","","","Provides the source of the security module error, if …","","","","","A container struct for security module-related …","Represents the available types of security modules in the …","","","","","","","","","","Returns the argument unchanged.","","Returns the argument unchanged.","Retrieves or creates an instance of a security module …","","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","Defines a common interface for cryptographic key …","Decrypts the given encrypted data using the cryptographic …","Encrypts the given data using the cryptographic key.","Signs the given data using the cryptographic key.","Verifies the signature of the given data using the …","Defines the interface for configuration data used by the …","","Defines the interface for a security module provider.","Creates a new cryptographic key identified by key_id.","Initializes the security module and returns a handle for …","Loads an existing cryptographic key identified by key_id.","Defines the interface for configuration data used by the …","Returns a reference to the underlying Any type.","","","","","","","","","","","Returns the argument unchanged.","","Calls U::from(self).","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","A struct defining the needed values for the create_key() …","A TPM-based cryptographic provider for managing …","","","","","","Creates a new cryptographic key identified by key_id.","Decrypts the data with the currently loaded key. The …","Encrypts the data with the currently loaded key. The …","","","Returns the argument unchanged.","Returns the argument unchanged.","This function ordinarily initialises the HSM. For our …","Calls U::from(self).","Calls U::from(self).","","","Loads an existing cryptographic key identified by key_id.","","","","","Constructs a new TpmProvider.","creates a new KnoxConfig At any time, either a …","","Signs data using the previously loaded cryptographic key.","","","","","","","","Verifies a signature against the provided data.","","","","Error occurring during TPM initialization, containing an …","Error indicating that an internal error occured, possibly …","Error related to I/O operations, wrapping a std::io::Error.","A trait to allow ergonomic conversions to TpmError","Represents errors that can occur when interacting with a …","Error indicating that an attempted operation is …","","","Provides a human-readable description of the TPM error.","Wrap any error in TpmError::InternalError the wrapped …","","","Returns the argument unchanged.","Calls U::from(self).","","","","","","","","Represents the TPM environment on Android platforms, with …","Enumerates the types of TPM available on Android platforms.","Android Provider using the Android Keystore API","Represents the Samsung Knox security platform with TPM …","Represents an unsupported or unknown TPM environment.","Manages instances of TPM providers based on the specified …","Represents the different environments where a Trusted …","","","","","","","","","","","Creates a new TPM provider instance based on the specified …","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","",""],"i":[0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,13,13,13,13,13,13,13,13,13,0,13,13,13,13,0,13,13,13,0,13,13,13,13,13,13,13,18,0,0,17,17,17,17,18,19,19,19,22,19,17,17,18,16,16,16,16,16,19,15,0,0,17,19,16,19,17,17,17,18,0,21,21,21,22,15,17,16,0,0,20,20,18,0,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,15,16,17,18,19,16,17,15,15,16,17,15,16,17,18,19,20,21,15,16,17,18,19,20,21,22,16,17,15,16,17,18,19,20,21,22,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,15,16,17,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,15,16,17,18,19,20,21,22,0,26,26,26,26,26,26,27,27,0,26,27,0,28,28,28,28,27,27,27,26,27,28,26,27,28,26,27,28,26,27,28,26,26,27,28,26,27,27,28,28,26,27,28,26,26,27,27,28,28,26,27,28,26,27,28,26,27,28,26,27,28,0,29,29,29,29,29,29,29,57,57,57,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,0,29,58,0,59,59,60,60,60,60,60,60,60,29,29,29,29,29,29,60,60,29,29,29,29,29,0,0,29,29,29,29,29,29,29,29,29,29,59,0,29,59,60,57,58,29,59,60,57,58,29,59,60,57,58,29,59,60,57,58,29,59,59,60,60,57,57,58,58,29,29,59,60,57,58,29,59,60,57,58,29,59,60,57,58,29,31,31,31,31,0,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,0,0,35,61,35,61,35,35,35,35,35,61,35,35,61,35,61,35,61,61,35,35,35,61,35,61,35,61,35,0,0,0,0,0,41,41,41,41,0,36,0,38,38,38,0,46,0,0,47,47,47,47,47,0,47,47,47,47,47,47,47,47,47,47,47,47,47,47,47,0,0,0,0,48,48,48,48,48,48,48,48,48,48,48,50,0,0,50,49,49,50,49,50,50,50,49,50,49,50,49,49,50,49,49,49,50,50,49,50,49,50,49,50,49,50,49,62,62,0,0,51,52,51,52,51,52,52,52,52,51,52,51,52,52,51,51,0,52,52,52,51,51,52,51,0,52,51,52,51,52,51,52,51,52,51,0,0,32,32,32,0,0,32,32,32,32,54,32,32,32,32,32,32,32,32,32,32,32,55,0,56,56,55,0,0,63,55,56,63,55,56,55,56,55,56,63,55,55,56,55,56,63,55,55,56,55,56,63,55,56,63,63,55,55,56,56,55,56,63,55,56,63,55,56,63,55,56],"f":"``````````````{ce{}{}}0{bb}{{ce}d{}{}}{{bb}f}{{bh}j}{cc{}}{{bc}dl}6{{cn}{{Ab{eA`}}}{}{}}{{cAd}{{Ab{eAf}}}{}{}}`8{c{{Ab{e}}}{}{}}0{cAh{}}``````````::{AjAj}9`{{Ajh}j}7{AlAj}`=56=443```````````````````````````````````````````````================{AnAn}{B`B`}{BbBb}{BdBd}{BfBf}{BhBh}{BjBj}{BlBl}{{ce}d{}{}}0000000{{}An}{{}B`}{{}Bb}{{}Bd}{{}Bf}{c{{Ab{B`}}}Bn}{c{{Ab{Bb}}}Bn}{An{{C`{Bb}}}}{An{{C`{B`}}}}{{B`B`}f}{{BbBb}f}{{Anh}j}{{B`h}j}{{Bbh}j}{{Bdh}j}{{Bfh}j}{{Bhh}j}{{Bjh}j}{cc{}}0000000{{B`c}dl}{{Bbc}dl}{ce{}{}}0000000{{cAd}{{Ab{eAf}}}{}{}}{{cn}{{Ab{eA`}}}{}{}}10101001010110{An{{C`{Aj}}}}{{B`c}AbCb}{{Bbc}AbCb}55555555{c{{Ab{e}}}{}{}}000000000000000{cAh{}}0000000````````````````````777777{CdCd}{CfCf}{ChCh}{{ce}d{}{}}00{{}Cd}{{Cdh}j}{{Cfh}j}{{Chh}j}{cc{}}0{AlCf}{AlCh}2{ce{}{}}00{{cn}{{Ab{eA`}}}{}{}}{{cAd}{{Ab{eAf}}}{}{}}1010222??????>>>``````````````````````````````````````````````````````````````````````{CjCl}333333333366666333332121212121{c{{Ab{e}}}{}{}}000000000{cAh{}}0000````````55{{Cnh}j}09{D`Cn}756{Cn{{C`{Db}}}}{cDd{}}554```9999{DfDf}{{ce}d{}{}}{{DfDf}f}{{Dfh}j}{cc{}}{ClDf}1{{DdDf{C`{{Dj{Dh}}}}}{{C`{{E`{{Dn{Dl}}}}}}}}{{Dfc}dl}{ce{}{}}0{{cn}{{Ab{eA`}}}{}{}}{{cAd}{{Ab{eAf}}}{}{}}012{c{{Ab{e}}}{}{}}000{cAh{}}0`````{{Eb{Ef{Ed}}}{{Ab{{Eh{Ed}}Cn}}}}00{{Eb{Ef{Ed}}{Ef{Ed}}}{{Ab{fCn}}}}`{Dhd}`{{DlCl{Dj{Ej}}}{{Ab{dCn}}}}{Dl{{Ab{dCn}}}}1`{ElEj}``{EnEj};;{EnEn}{{ce}d{}{}}`{{}En}{{Enh}j}{cc{}}`{ce{}{}}``{{cn}{{Ab{eA`}}}{}{}}{{cAd}{{Ab{eAf}}}{}{}}{{AnBdCd{Eh{b}}}{{Dj{El}}}}`3{c{{Ab{e}}}{}{}}0{cAh{}}````55{{F`h}j}7654{F`d}332````{FbEj}8888{FdFd}={{Fbh}j}{{Fdh}j}<<`;;`:9:9`;777766`````{FfEj}<<<<{{FhCl{Dj{Ej}}}{{Ab{dCn}}}}{{Fh{Ef{Ed}}}{{Ab{{Eh{Ed}}Cn}}}}0{{Fhh}j}{{Ffh}j}{cc{}}0{Fh{{Ab{dCn}}}}{ce{}{}}0``6{{cn}{{Ab{eA`}}}{}{}}{{cAd}{{Ab{eAf}}}{}{}}10{{}Fh}{{{C`{An}}{C`{Bd}}Fj}{{Ab{FfCn}}}}`9`{c{{Ab{e}}}{}{}}000{cAh{}}0{{Fh{Ef{Ed}}{Ef{Ed}}}{{Ab{fCn}}}}`````````77{D`Dd}{Fl{{Ab{cD`}}}{}}{{D`h}j}0<:98{D`{{C`{Db}}}}{cDd{}}776```````<<<<<<{FnFn}{G`G`}{{ce}d{}{}}0{{DdFn}{{E`{{Dn{Dl}}}}}}{{}Fn}{{FnFn}f}{{G`G`}f}{{Fnh}j}{{G`h}j}{cc{}}0{ClFn}1{{Fnc}dl}{{G`c}dl}{ce{}{}}00{{cAd}{{Ab{eAf}}}{}{}}{{cn}{{Ab{eA`}}}{}{}}101022{c{{Ab{e}}}{}{}}00000{cAh{}}00","c":[],"p":[[6,"KeyUsage",8],[1,"unit"],[1,"bool"],[5,"Formatter",649],[8,"Result",649],[10,"Hasher",650],[5,"JNIEnv",651],[6,"Error",652],[6,"Result",653],[5,"JNIEnv",651],[6,"Error",652],[5,"TypeId",654],[6,"KeyBits",30],[1,"u32"],[6,"AsymmetricEncryption",56],[6,"EccSchemeAlgorithm",56],[6,"EccCurves",56],[6,"BlockCiphers",56],[6,"SymmetricMode",56],[6,"TripleDesNumKeys",56],[6,"Rc2KeyBits",56],[6,"StreamCiphers",56],[10,"Deserializer",655],[6,"Option",656],[10,"Serializer",657],[6,"Hash",222],[6,"Sha2Bits",222],[6,"Sha3Bits",222],[6,"OidType",285],[1,"str"],[6,"SecurityModuleError",400],[6,"TpmError",579],[10,"Error",658],[5,"String",659],[6,"SecurityModule",422],[10,"LogConfig",460],[5,"Box",660],[10,"Provider",462],[5,"Mutex",661],[5,"Arc",662],[10,"KeyHandle",455],[1,"u8"],[1,"slice"],[5,"Vec",663],[10,"Any",654],[10,"ProviderConfig",466],[5,"TpmConfig",468],[5,"DefaultAndroidLogger",494],[5,"AndroidConfig",506],[6,"EncryptionMode",506],[5,"KnoxConfig",540],[5,"KnoxProvider",540],[5,"JavaVM",664],[10,"ToTpmError",579],[6,"TpmType",600],[6,"AndroidTpmType",600],[6,"X509Type",285],[6,"ObjectIdentifiers",285],[6,"PkiStandards",285],[6,"PkcsType",285],[5,"SecModules",422],[15,"ASym",538],[5,"TpmInstance",600]],"b":[[410,"impl-Debug-for-SecurityModuleError"],[411,"impl-Display-for-SecurityModuleError"],[589,"impl-Display-for-TpmError"],[590,"impl-Debug-for-TpmError"]]}]\ +]')); +if (typeof exports !== 'undefined') exports.searchIndex = searchIndex; +else if (window.initSearch) window.initSearch(searchIndex); diff --git a/Documentation/RustDoc/settings.html b/Documentation/RustDoc/settings.html new file mode 100644 index 00000000..b00c88f2 --- /dev/null +++ b/Documentation/RustDoc/settings.html @@ -0,0 +1,2 @@ +Settings +

    Rustdoc settings

    Back
    \ No newline at end of file diff --git a/Documentation/RustDoc/src-files.js b/Documentation/RustDoc/src-files.js new file mode 100644 index 00000000..6563688e --- /dev/null +++ b/Documentation/RustDoc/src-files.js @@ -0,0 +1,4 @@ +var srcIndex = new Map(JSON.parse('[\ +["crypto_layer",["",[["common",[["crypto",[["algorithms",[],["encryption.rs","hashes.rs","mod.rs"]],["pkcs",[],["mod.rs","standards.rs"]]],["mod.rs"]],["traits",[],["key_handle.rs","log_config.rs","mod.rs","module_provider.rs","module_provider_config.rs"]]],["error.rs","factory.rs","mod.rs"]],["tpm",[["android",[["knox",[],["interface.rs","key_handle.rs","mod.rs","provider.rs"]],["wrapper",[["key_generation",[],["builder.rs","key.rs","key_gen_parameter_spec.rs","key_generator.rs","key_pair.rs","key_pair_generator.rs","mod.rs","secure_random.rs"]],["key_store",[],["cipher.rs","key_store.rs","mod.rs","signature.rs"]]],["mod.rs"]]],["android_logger.rs","config.rs","error.rs","mod.rs","utils.rs"]],["core",[],["error.rs","instance.rs","mod.rs"]]],["mod.rs"]]],["lib.rs"]]]\ +]')); +createSrcSidebar(); diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/encryption.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/encryption.rs.html new file mode 100644 index 00000000..6e1d4eb8 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/encryption.rs.html @@ -0,0 +1,785 @@ +encryption.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +197
    +198
    +199
    +200
    +201
    +202
    +203
    +204
    +205
    +206
    +207
    +208
    +209
    +210
    +211
    +212
    +213
    +214
    +215
    +216
    +217
    +218
    +219
    +220
    +221
    +222
    +223
    +224
    +225
    +226
    +227
    +228
    +229
    +230
    +231
    +232
    +233
    +234
    +235
    +236
    +237
    +238
    +239
    +240
    +241
    +242
    +243
    +244
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    +254
    +255
    +256
    +257
    +258
    +259
    +260
    +261
    +262
    +263
    +264
    +265
    +266
    +267
    +268
    +269
    +270
    +271
    +272
    +273
    +274
    +275
    +276
    +277
    +278
    +279
    +280
    +281
    +282
    +283
    +284
    +285
    +286
    +287
    +288
    +289
    +290
    +291
    +292
    +293
    +294
    +295
    +296
    +297
    +298
    +299
    +300
    +301
    +302
    +303
    +304
    +305
    +306
    +307
    +308
    +309
    +310
    +311
    +312
    +313
    +314
    +315
    +316
    +317
    +318
    +319
    +320
    +321
    +322
    +323
    +324
    +325
    +326
    +327
    +328
    +329
    +330
    +331
    +332
    +333
    +334
    +335
    +336
    +337
    +338
    +339
    +340
    +341
    +342
    +343
    +344
    +345
    +346
    +347
    +348
    +349
    +350
    +351
    +352
    +353
    +354
    +355
    +356
    +357
    +358
    +359
    +360
    +361
    +362
    +363
    +364
    +365
    +366
    +367
    +368
    +369
    +370
    +371
    +372
    +373
    +374
    +375
    +376
    +377
    +378
    +379
    +380
    +381
    +382
    +383
    +384
    +385
    +386
    +387
    +388
    +389
    +390
    +391
    +
    use super::KeyBits;
    +use serde::{Deserialize, Serialize};
    +
    +/// Represents the available encryption algorithms.
    +///
    +/// This enum provides a C-compatible representation of different encryption
    +/// methods supported by the system, including asymmetric algorithms like RSA and ECC.
    +/// It is designed to be extensible, allowing for the addition
    +/// of more encryption algorithms in the future.
    +///
    +/// # Examples
    +///
    +/// Basic usage for RSA (assuming `RsaBits` is defined):
    +///
    +/// ```
    +/// use tpm_poc::common::crypto::algorithms::{KeyBits, encryption::AsymmetricEncryption};
    +///
    +/// let encryption_method = AsymmetricEncryption::Rsa(KeyBits::Bits2048);
    +/// ```
    +///
    +/// Basic usage for ECC:
    +///
    +/// ```
    +/// use tpm_poc::common::crypto::algorithms::encryption::{AsymmetricEncryption, EccSchemeAlgorithm, EccCurves};
    +///
    +/// let encryption_method = AsymmetricEncryption::Ecc(EccSchemeAlgorithm::EcDsa(EccCurves::Secp256k1));
    +/// ```
    +///
    +/// # Note
    +///
    +/// This enum uses `#[repr(C)]` to ensure that it has the same memory layout as a C enum,
    +/// facilitating interfacing with C code or when ABI compatibility is required.
    +
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum AsymmetricEncryption {
    +    /// RSA encryption with selectable key sizes.
    +    ///
    +    /// Allows specifying the key size for RSA encryption through the `KeyBits` enum,
    +    /// supporting various standard key lengths for different security needs. RSA is widely used
    +    /// for secure data transmission and is known for its simplicity and strong security properties,
    +    /// provided a sufficiently large key size is used.
    +    Rsa(KeyBits),
    +
    +    /// Represents Elliptic Curve Cryptography (ECC) encryption.
    +    ///
    +    /// ECC offers encryption methods based on elliptic curves over finite fields,
    +    /// potentially including various algorithms and curves such as P-256, P-384, and others.
    +    /// ECC is known for providing the same level of security as RSA but with smaller key sizes,
    +    /// leading to faster computations and lower power consumption.
    +    Ecc(EccSchemeAlgorithm),
    +}
    +
    +impl Default for AsymmetricEncryption {
    +    fn default() -> Self {
    +        Self::Ecc(Default::default())
    +    }
    +}
    +
    +impl AsymmetricEncryption {
    +    /// Retrieves the RSA key size if the asymmetric encryption method is RSA.
    +    ///
    +    /// # Returns
    +    ///
    +    /// An `Option<KeyBits>` representing the key size of the RSA encryption. Returns `None`
    +    /// if the encryption method is not RSA.
    +    pub fn rsa_key_bits(&self) -> Option<KeyBits> {
    +        match self {
    +            AsymmetricEncryption::Rsa(key_bits) => Some(*key_bits),
    +            _ => None,
    +        }
    +    }
    +
    +    /// Retrieves the ECC scheme algorithm if the asymmetric encryption method is ECC.
    +    ///
    +    /// This method extracts the specific ECC scheme algorithm used, such as ECDSA, ECDH, etc.
    +    ///
    +    /// # Returns
    +    ///
    +    /// An `Option<EccSchemeAlgorithm>` representing the ECC scheme. Returns `None`
    +    /// if the encryption method is not ECC.
    +    pub fn ecc_scheme(&self) -> Option<EccSchemeAlgorithm> {
    +        match self {
    +            AsymmetricEncryption::Ecc(ecc_scheme) => Some(*ecc_scheme),
    +            _ => None,
    +        }
    +    }
    +
    +    /// Retrieves the elliptic curve used if the asymmetric encryption method is ECC.
    +    ///
    +    /// For ECC schemes that specify a curve, this method returns the curve being used. It supports
    +    /// multiple ECC schemes and their associated curves.
    +    ///
    +    /// # Returns
    +    ///
    +    /// An `Option<EccCurves>` representing the elliptic curve used. Returns `None`
    +    /// if the encryption method is not ECC or if the ECC scheme does not specify a curve.
    +    pub fn ecc_curve(&self) -> Option<EccCurves> {
    +        match self {
    +            AsymmetricEncryption::Ecc(ecc_scheme) => match ecc_scheme {
    +                EccSchemeAlgorithm::EcDsa(curve) => Some(*curve),
    +                EccSchemeAlgorithm::EcDh(curve) => Some(*curve),
    +                EccSchemeAlgorithm::EcDaa(curve) => Some(*curve),
    +                EccSchemeAlgorithm::Sm2(curve) => Some(*curve),
    +                EccSchemeAlgorithm::EcSchnorr(curve) => Some(*curve),
    +                EccSchemeAlgorithm::EcMqv(curve) => Some(*curve),
    +                EccSchemeAlgorithm::Null => None,
    +            },
    +            _ => None,
    +        }
    +    }
    +}
    +
    +/// Enum representing the ECC scheme interface type.
    +///
    +/// Defines various algorithms that can be used in conjunction with Elliptic Curve Cryptography (ECC),
    +/// including signature schemes, key exchange protocols, and more. This allows for flexible cryptographic
    +/// configurations tailored to different security requirements and performance constraints.
    +///
    +/// # Examples
    +///
    +/// Selecting an ECC scheme:
    +///
    +/// ```
    +/// use tpm_poc::common::crypto::algorithms::encryption::EccSchemeAlgorithm;
    +/// use tpm_poc::common::crypto::algorithms::encryption::EccCurves;
    +///
    +/// let scheme = EccSchemeAlgorithm::EcDsa(EccCurves::Secp256k1);
    +/// ```
    +#[repr(C)]
    +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
    +pub enum EccSchemeAlgorithm {
    +    /// ECDSA: Elliptic Curve Digital Signature Algorithm.
    +    EcDsa(EccCurves),
    +    /// ECDH: Elliptic Curve Diffie-Hellman for key agreement.
    +    EcDh(EccCurves),
    +    /// ECDAA: Elliptic Curve Direct Anonymous Attestation.
    +    EcDaa(EccCurves),
    +    /// SM2: A Chinese cryptographic standard for digital signatures and key exchange.
    +    Sm2(EccCurves),
    +    /// EC-Schnorr: A Schnorr signature scheme variant using elliptic curves.
    +    EcSchnorr(EccCurves),
    +    /// ECMQV: Elliptic Curve Menezes-Qu-Vanstone, a key agreement scheme.
    +    EcMqv(EccCurves),
    +    /// Null: A placeholder or default value indicating no ECC scheme.
    +    Null,
    +}
    +
    +impl Default for EccSchemeAlgorithm {
    +    fn default() -> Self {
    +        Self::EcDsa(EccCurves::Curve25519)
    +    }
    +}
    +
    +/// Specifies the curve types for Elliptic Curve Digital Signature Algorithm (ECDSA).
    +///
    +/// Lists the supported elliptic curve specifications for ECDSA, affecting security and performance.
    +/// Includes both NIST P-curves and others like secp256k1 and Brainpool curves.
    +///
    +/// # Examples
    +///
    +/// Selecting an ECDSA curve:
    +///
    +/// ```
    +/// use tpm_poc::common::crypto::algorithms::encryption::EccCurves;
    +///
    +/// let curve_type = EccCurves::Secp256k1;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Uses `#[repr(C)]` for C language compatibility.
    +#[repr(C)]
    +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
    +pub enum EccCurves {
    +    /// NIST P-256 curve.
    +    P256,
    +    /// NIST P-384 curve.
    +    P384,
    +    /// NIST P-521 curve.
    +    P521,
    +    /// secp256k1 curve, commonly used in blockchain technologies.
    +    Secp256k1,
    +    /// Brainpool P256r1 curve.
    +    BrainpoolP256r1,
    +    /// Brainpool P384r1 curve.
    +    BrainpoolP384r1,
    +    /// Brainpool P512r1 curve.
    +    BrainpoolP512r1,
    +    /// Brainpool P638 curve.
    +    BrainpoolP638,
    +    /// Curve25519, popular for its security and performance.
    +    #[default]
    +    Curve25519,
    +    /// Curve448, known for high security and efficiency.
    +    Curve448,
    +    /// FRP256v1, a French curve providing strong security and performance.
    +    Frp256v1,
    +}
    +
    +/// Represents the available block cipher algorithms.
    +///
    +/// This enum provides a C-compatible representation of various block cipher algorithms supported,
    +/// including AES, Triple DES, DES, RC2, and Camellia. Each algorithm can be configured with specific modes of operation and key sizes.
    +/// It is designed for flexibility, allowing for easy extension to include additional block cipher algorithms.
    +///
    +/// # Examples
    +///
    +/// Using `BlockCiphers` with AES in CBC mode and a 256-bit key:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::{KeyBits,encryption::{BlockCiphers, SymmetricMode}};
    +///
    +/// let cipher = BlockCiphers::Aes(SymmetricMode::Cbc, KeyBits::Bits256);
    +/// ```
    +///
    +/// Using `BlockCiphers` with Triple DES in EDE3 mode:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::encryption::{BlockCiphers, TripleDesNumKeys};
    +///
    +/// let cipher = BlockCiphers::TripleDes(TripleDesNumKeys::Tdes3);
    +/// ```
    +///
    +/// # Note
    +///
    +/// Marked with `#[repr(C)]` to ensure it has the same memory layout as a C enum,
    +/// facilitating ABI compatibility and interfacing with C code.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum BlockCiphers {
    +    /// AES (Advanced Encryption Standard) block cipher with selectable key sizes and modes.
    +    Aes(SymmetricMode, KeyBits),
    +    /// Triple DES block cipher, either in two-key or three-key configurations.
    +    TripleDes(TripleDesNumKeys),
    +    /// DES (Data Encryption Standard) block cipher, now considered insecure for many applications.
    +    Des,
    +    /// RC2 block cipher with selectable key sizes.
    +    Rc2(Rc2KeyBits),
    +    /// Camellia block cipher with selectable key sizes.
    +    Camellia(SymmetricMode, KeyBits),
    +}
    +
    +impl Default for BlockCiphers {
    +    fn default() -> Self {
    +        Self::Aes(SymmetricMode::Gcm, KeyBits::Bits4096)
    +    }
    +}
    +
    +/// Specifies the modes of operation for symmetric block ciphers.
    +///
    +/// This enum lists the supported modes of operation, such as GCM, CCM, ECB, CBC, CFB, OFB, and CTR.
    +/// These modes determine how block ciphers process plaintext and ciphertext, affecting security and performance characteristics.
    +///
    +/// # Examples
    +///
    +/// Selecting AES in GCM mode:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::encryption::SymmetricMode;
    +///
    +/// let mode = SymmetricMode::Gcm;
    +/// ```
    +///
    +/// # Note
    +///
    +/// `#[repr(C)]` attribute is used for C compatibility.
    +#[repr(C)]
    +#[derive(Clone, Debug, Default, Copy)]
    +pub enum SymmetricMode {
    +    /// AES in Galois/Counter Mode (GCM) with selectable key sizes.
    +    /// GCM is preferred for its performance and security, providing both encryption and authentication.
    +    #[default]
    +    Gcm,
    +
    +    /// AES in Counter with CBC-MAC (CCM) mode with selectable key sizes.
    +    /// CCM combines counter mode encryption with CBC-MAC authentication, suitable for constrained environments.
    +    Ccm,
    +
    +    /// AES in Electronic Codebook (ECB) mode.
    +    /// ECB encrypts each block of data independently. Due to its deterministic nature, it's considered insecure for most uses.
    +    Ecb,
    +
    +    /// AES in Cipher Block Chaining (CBC) mode.
    +    /// CBC mode introduces dependencies between blocks for better security but requires proper IV management.
    +    Cbc,
    +
    +    /// AES in Cipher Feedback (CFB) mode.
    +    /// CFB mode turns AES into a stream cipher, allowing for encryption of partial blocks. It's useful for streaming data.
    +    Cfb,
    +
    +    /// AES in Output Feedback (OFB) mode.
    +    /// OFB mode also converts AES into a stream cipher but generates keystream blocks independently of the plaintext.
    +    Ofb,
    +
    +    /// AES in Counter (CTR) mode.
    +    /// CTR mode encrypts a sequence of counters, offering high throughput and parallelization capabilities.
    +    Ctr,
    +}
    +
    +/// Specifies the number of keys used in Triple DES configurations.
    +///
    +/// This enum provides options for two-key (Ede2) and three-key (Ede3) Triple DES configurations.
    +/// The choice between two-key and three-key configurations affects the security level and performance of the encryption process.
    +///
    +/// # Examples
    +///
    +/// Selecting a Triple DES configuration with three keys:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::encryption::TripleDesNumKeys;
    +///
    +/// let des_config = TripleDesNumKeys::Tdes3;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Uses `#[repr(C)]` for C language compatibility.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum TripleDesNumKeys {
    +    /// Two-key Triple DES, using two different keys for encryption.
    +    Tdes2,
    +    /// Three-key Triple DES, providing enhanced security with three different keys.
    +    Tdes3,
    +}
    +
    +/// Specifies the key sizes for the RC2 block cipher.
    +///
    +/// This enum lists the supported key sizes for RC2, such as 40, 64, and 128 bits.
    +/// The selection of key size impacts the security and compatibility of the encryption process.
    +///
    +/// # Examples
    +///
    +/// Selecting an RC2 key size of 128 bits:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::encryption:: Rc2KeyBits;
    +///
    +/// let key_size = Rc2KeyBits::Rc2_128;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Marked with `#[repr(C)]` to ensure compatibility with C-based environments.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum Rc2KeyBits {
    +    /// RC2 with a 40-bit key.
    +    Rc2_40,
    +    /// RC2 with a 64-bit key.
    +    Rc2_64,
    +    /// RC2 with a 128-bit key, offering the highest level of security among the options.
    +    Rc2_128,
    +}
    +
    +/// Represents the available stream cipher algorithms.
    +///
    +/// This enum provides a C-compatible representation of stream cipher algorithms such as RC4 and ChaCha20.
    +/// Stream ciphers encrypt plaintext one bit or byte at a time, offering different security and performance characteristics compared to block ciphers.
    +/// ChaCha20 is recommended for new applications due to its strong security profile.
    +///
    +/// # Examples
    +///
    +/// Using ChaCha20 stream cipher:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::encryption::StreamCiphers;
    +///
    +/// let cipher = StreamCiphers::Chacha20;
    +/// ```
    +///
    +/// # Note
    +///
    +/// `#[repr(C)]` attribute is used for C compatibility, important for interoperability with C-based systems.
    +#[repr(C)]
    +#[derive(Clone)]
    +pub enum StreamCiphers {
    +    /// RC4 stream cipher.
    +    ///
    +    /// Once widely used, RC4 is now considered insecure due to vulnerabilities that have
    +    /// been discovered over time. It is included here for legacy support and should not
    +    /// be used for new applications requiring secure encryption.
    +    Rc4,
    +    /// ChaCha20 stream cipher.
    +    ///
    +    /// Provides strong security and high performance, making it suitable for a wide
    +    /// range of modern applications. ChaCha20 is recommended for use when a secure and
    +    /// efficient stream cipher is required.
    +    Chacha20,
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/hashes.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/hashes.rs.html new file mode 100644 index 00000000..bb22ec66 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/hashes.rs.html @@ -0,0 +1,373 @@ +hashes.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +
    /// Represents the available hashing algorithms.
    +///
    +/// This enum provides a C-compatible representation of various hashing algorithms,
    +/// including both historically significant and modern, secure algorithms.
    +///
    +/// When choosing a hashing algorithm, consider its security level and known vulnerabilities.
    +/// Algorithms like SHA-1, MD2, MD4, and MD5 are considered insecure for most cryptographic
    +/// purposes due to practical collision attacks and should be avoided for new applications.
    +/// Prefer using more secure algorithms like SHA-2 or SHA-3 for cryptographic purposes.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum Hash {
    +    /// SHA-1 hashing algorithm.
    +    ///
    +    /// Considered insecure for most cryptographic purposes now due to vulnerabilities
    +    /// that allow for practical collision attacks.
    +    Sha1,
    +    /// SHA-2 family of hashing algorithms with selectable digest sizes.
    +    Sha2(Sha2Bits),
    +    /// SHA-3 family of hashing algorithms, also known as Keccak, with selectable digest sizes.
    +    Sha3(Sha3Bits),
    +    /// MD2 hashing algorithm.
    +    ///
    +    /// Considered cryptographically broken and unsuitable for further use due to significant
    +    /// vulnerabilities.
    +    Md2,
    +    /// MD4 hashing algorithm.
    +    ///
    +    /// Faster but less secure than MD5; considered broken due to vulnerabilities to collision attacks.
    +    Md4,
    +    /// MD5 hashing algorithm.
    +    ///
    +    /// Widely used historically but can no longer be considered secure against collision attacks,
    +    /// despite its continued use in non-cryptographic contexts like checksums.
    +    Md5,
    +    /// RIPEMD-160 hashing algorithm.
    +    ///
    +    /// Designed to be a secure alternative to MD4 and MD5. It offers a good balance
    +    /// of security for applications requiring a hash function more resilient to the
    +    /// vulnerabilities affecting earlier Message Digest algorithms.
    +    Ripemd160,
    +}
    +
    +impl Default for Hash {
    +    fn default() -> Self {
    +        Self::Sha2(Sha2Bits::Sha512)
    +    }
    +}
    +
    +/// Specifies the digest sizes for the SHA-2 family of hashing algorithms.
    +///
    +/// This enum lists the supported digest sizes for SHA-2, providing a range of options
    +/// for different security and performance needs. The larger the digest size, the higher
    +/// the security level and collision resistance, but with a potential decrease in performance.
    +/// Selecting the appropriate digest size depends on the specific requirements of the application,
    +/// balancing security against computational overhead.
    +///
    +/// # Examples
    +///
    +/// Selecting a SHA-2 digest size:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::hashes::Sha2Bits;
    +///
    +/// let digest_size = Sha2Bits::Sha512;
    +/// ```
    +///
    +/// # Note
    +///
    +/// `#[repr(C)]` attribute is used for C compatibility, facilitating interoperability with C-based systems.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum Sha2Bits {
    +    /// 224-bit digest size.
    +    Sha224,
    +    /// 256-bit digest size, commonly used for its balance of security and performance.
    +    Sha256,
    +    /// 384-bit digest size.
    +    Sha384,
    +    /// 512-bit digest size, offering high security for sensitive applications.
    +    Sha512,
    +    /// 224-bit digest size variant of SHA-512, designed for compatibility with SHA-224.
    +    Sha512_224,
    +    /// 256-bit digest size variant of SHA-512, optimized for security and efficiency.
    +    Sha512_256,
    +}
    +
    +/// Implements the `From` trait to convert a `u32` value to the corresponding `Sha2Bits` variant.
    +///
    +/// This allows for easy conversion from integer values to the enum variants, which can be useful
    +/// when working with external data sources or APIs that represent digest sizes as integers.
    +impl From<u32> for Sha2Bits {
    +    fn from(value: u32) -> Self {
    +        match value {
    +            224 => Self::Sha224,
    +            256 => Self::Sha256,
    +            384 => Self::Sha384,
    +            512 => Self::Sha512,
    +            _ => unimplemented!(),
    +        }
    +    }
    +}
    +
    +/// Implements the `From` trait to convert a `Sha2Bits` variant to its corresponding `u32` value.
    +///
    +/// This can be useful when working with APIs or systems that expect digest sizes as integer values
    +/// instead of enum variants.
    +impl From<Sha2Bits> for u32 {
    +    fn from(value: Sha2Bits) -> Self {
    +        match value {
    +            Sha2Bits::Sha224 => 224,
    +            Sha2Bits::Sha256 => 256,
    +            Sha2Bits::Sha384 => 384,
    +            Sha2Bits::Sha512 => 512,
    +            _ => unimplemented!(),
    +        }
    +    }
    +}
    +
    +/// Specifies the digest sizes for the SHA-3 family of hashing algorithms.
    +///
    +/// SHA-3, also known as Keccak, offers a range of digest sizes to accommodate various
    +/// security levels and performance requirements. As a newer standard compared to SHA-2,
    +/// SHA-3 introduces a different cryptographic design that is resilient against many of the
    +/// vulnerabilities that affect older hashing algorithms. Choosing the correct digest size
    +/// allows developers to optimize for security and efficiency based on their specific needs.
    +/// A larger digest size generally provides higher security and collision resistance but may
    +/// come with a performance trade-off.
    +///
    +/// # Examples
    +///
    +/// Selecting a SHA-3 digest size:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::algorithms::hashes::Sha3Bits;
    +///
    +/// let digest_size = Sha3Bits::Sha3_384;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Uses `#[repr(C)]` for C language compatibility, important for interoperability with C-based systems.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum Sha3Bits {
    +    /// 224-bit digest size for SHA-3.
    +    Sha3_224,
    +    /// 256-bit digest size for SHA-3
    +    Sha3_256,
    +    /// 384-bit digest size for SHA-3
    +    Sha3_384,
    +    /// 512-bit digest size for SHA-3
    +    Sha3_512,
    +}
    +
    +/// Implements the `From` trait to convert a `u32` value to the corresponding `Sha3Bits` variant.
    +///
    +/// This allows for easy conversion from integer values to the enum variants, which can be useful
    +/// when working with external data sources or APIs that represent digest sizes as integers.
    +impl From<u32> for Sha3Bits {
    +    fn from(value: u32) -> Self {
    +        match value {
    +            224 => Self::Sha3_224,
    +            256 => Self::Sha3_256,
    +            384 => Self::Sha3_384,
    +            512 => Self::Sha3_512,
    +            _ => unimplemented!(),
    +        }
    +    }
    +}
    +
    +/// Implements the `From` trait to convert a `Sha3Bits` variant to its corresponding `u32` value.
    +///
    +/// This can be useful when working with APIs or systems that expect digest sizes as integer values
    +/// instead of enum variants.
    +impl From<Sha3Bits> for u32 {
    +    fn from(value: Sha3Bits) -> Self {
    +        match value {
    +            Sha3Bits::Sha3_224 => 224,
    +            Sha3Bits::Sha3_256 => 256,
    +            Sha3Bits::Sha3_384 => 384,
    +            Sha3Bits::Sha3_512 => 512,
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/mod.rs.html new file mode 100644 index 00000000..6e997506 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/algorithms/mod.rs.html @@ -0,0 +1,137 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +
    pub mod encryption;
    +pub mod hashes;
    +
    +/// Represents the bit length of a cryptographic key.
    +///
    +/// This enum defines various key bit lengths commonly used in cryptography.
    +/// It provides a convenient way to specify and work with different key sizes.
    +///
    +/// The available key bit lengths are:
    +///
    +/// - `Bits128`: 128-bit key length
    +/// - `Bits192`: 192-bit key length
    +/// - `Bits256`: 256-bit key length
    +/// - `Bits512`: 512-bit key length
    +/// - `Bits1024`: 1024-bit key length
    +/// - `Bits2048`: 2048-bit key length
    +/// - `Bits3072`: 3072-bit key length
    +/// - `Bits4096`: 4096-bit key length
    +/// - `Bits8192`: 8192-bit key length
    +///
    +/// This enum can be converted to and from `u32` values using the `From` trait implementations.
    +#[repr(C)]
    +#[derive(Clone, Debug, Copy)]
    +pub enum KeyBits {
    +    Bits128,
    +    Bits192,
    +    Bits256,
    +    Bits512,
    +    Bits1024,
    +    Bits2048,
    +    Bits3072,
    +    Bits4096,
    +    Bits8192,
    +}
    +
    +impl From<KeyBits> for u32 {
    +    fn from(value: KeyBits) -> Self {
    +        match value {
    +            KeyBits::Bits128 => 128,
    +            KeyBits::Bits192 => 192,
    +            KeyBits::Bits256 => 256,
    +            KeyBits::Bits512 => 512,
    +            KeyBits::Bits1024 => 1024,
    +            KeyBits::Bits2048 => 2048,
    +            KeyBits::Bits3072 => 3072,
    +            KeyBits::Bits4096 => 4096,
    +            KeyBits::Bits8192 => 8192,
    +        }
    +    }
    +}
    +
    +impl From<u32> for KeyBits {
    +    fn from(value: u32) -> Self {
    +        match value {
    +            128 => KeyBits::Bits128,
    +            192 => KeyBits::Bits192,
    +            256 => KeyBits::Bits256,
    +            512 => KeyBits::Bits512,
    +            1024 => KeyBits::Bits1024,
    +            2048 => KeyBits::Bits2048,
    +            3072 => KeyBits::Bits3072,
    +            4096 => KeyBits::Bits4096,
    +            8192 => KeyBits::Bits8192,
    +            _ => unimplemented!(),
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/mod.rs.html new file mode 100644 index 00000000..8de9d420 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/mod.rs.html @@ -0,0 +1,25 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +
    pub mod algorithms;
    +pub mod pkcs;
    +
    +#[repr(C)]
    +#[derive(Eq, Hash, PartialEq, Clone, Debug, Copy)]
    +pub enum KeyUsage {
    +    ClientAuth,
    +    Decrypt,
    +    SignEncrypt,
    +    CreateX509,
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/mod.rs.html new file mode 100644 index 00000000..f2738b3d --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/mod.rs.html @@ -0,0 +1,5 @@ +mod.rs - source +
    1
    +
    pub mod standards;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/standards.rs.html b/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/standards.rs.html new file mode 100644 index 00000000..891c8a39 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/crypto/pkcs/standards.rs.html @@ -0,0 +1,605 @@ +standards.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +197
    +198
    +199
    +200
    +201
    +202
    +203
    +204
    +205
    +206
    +207
    +208
    +209
    +210
    +211
    +212
    +213
    +214
    +215
    +216
    +217
    +218
    +219
    +220
    +221
    +222
    +223
    +224
    +225
    +226
    +227
    +228
    +229
    +230
    +231
    +232
    +233
    +234
    +235
    +236
    +237
    +238
    +239
    +240
    +241
    +242
    +243
    +244
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    +254
    +255
    +256
    +257
    +258
    +259
    +260
    +261
    +262
    +263
    +264
    +265
    +266
    +267
    +268
    +269
    +270
    +271
    +272
    +273
    +274
    +275
    +276
    +277
    +278
    +279
    +280
    +281
    +282
    +283
    +284
    +285
    +286
    +287
    +288
    +289
    +290
    +291
    +292
    +293
    +294
    +295
    +296
    +297
    +298
    +299
    +300
    +301
    +
    /// Represents the various Public Key Infrastructure (PKI) standards.
    +///
    +/// This enum provides a C-compatible representation of different PKI standards,
    +/// including PKCS (Public-Key Cryptography Standards), X.509, and PEM (Privacy-Enhanced Mail).
    +/// These standards cover a wide range of purposes, from cryptographic keys and certificates
    +/// storage to secure communication protocols.
    +///
    +/// # Examples
    +///
    +/// Using `PkiStandards` with PKCS#1:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::{PkiStandards, PkcsType};
    +///
    +/// let pki_standard = PkiStandards::Pkcs(PkcsType::Pkcs1);
    +/// ```
    +///
    +/// Using `PkiStandards` with X.509 Certificates:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::{PkiStandards, X509Type};
    +///
    +/// let pki_standard = PkiStandards::X509(X509Type::Certificate);
    +/// ```
    +///
    +/// # Note
    +///
    +/// The `#[repr(C)]` attribute ensures C compatibility, making these enums suitable for
    +/// interfacing with C-based systems. They encompass a broad range of PKI applications,
    +/// from encryption and digital signatures to certificate management.
    +#[repr(C)]
    +pub enum PkiStandards {
    +    /// PKCS (Public-Key Cryptography Standards) related operations.
    +    ///
    +    /// Wraps various PKCS standards, each focusing on different aspects of public-key cryptography.
    +    Pkcs(PkcsType),
    +    /// X.509 related operations, including certificates and revocation lists.
    +    X509(X509Type),
    +    /// PEM (Privacy-Enhanced Mail) format for storing and sending cryptographic keys and certificates.
    +    Pem,
    +}
    +
    +/// Enumerates the PKCS (Public-Key Cryptography Standards) types.
    +///
    +/// Specifies the different PKCS standards, covering a wide array of cryptographic
    +/// functionalities, including key exchange, encryption, and digital signatures.
    +///
    +/// # Examples
    +///
    +/// Selecting a PKCS type for RSA cryptography:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::PkcsType;
    +///
    +/// let pkcs_type = PkcsType::Pkcs1;
    +/// ```
    +///
    +/// # Note
    +///
    +/// `#[repr(C)]` attribute for C compatibility.
    +#[repr(C)]
    +pub enum PkcsType {
    +    /// RSA Cryptography Standard.
    +    Pkcs1,
    +    /// Diffie-Hellman Key Agreement Standard.
    +    Pkcs3,
    +    /// Password-Based Cryptography Standard.
    +    Pkcs5,
    +    /// Cryptographic Message Syntax Standard.
    +    Pkcs7,
    +    /// Private-Key Information Syntax Standard.
    +    Pkcs8,
    +    /// Selected Attribute Types.
    +    Pkcs9,
    +    /// Certification Request Syntax Standard.
    +    Pkcs10,
    +    /// Cryptographic Token Interface (Cryptoki).
    +    Pkcs11,
    +    /// Personal Information Exchange Syntax Standard.
    +    Pkcs12,
    +}
    +
    +/// Enumerates the types within the X.509 standard.
    +///
    +/// Specifies the different elements associated with X.509, a standard for creating
    +/// a public key infrastructure for digital certificates and public-key encryption.
    +///
    +/// # Examples
    +///
    +/// Selecting an X.509 type for certificates:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::X509Type;
    +///
    +/// let x509_type = X509Type::Certificate;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Uses `#[repr(C)]` for compatibility with C language standards, facilitating use
    +/// in systems where interoperability with C is required.
    +#[repr(C)]
    +pub enum X509Type {
    +    /// Represents an X.509 certificate.
    +    Certificate,
    +    /// Represents an X.509 Certificate Revocation List (CRL).
    +    CertificateRevocationList,
    +    /// Represents an X.509 Certificate Signing Request (CSR).
    +    CertificateSigningRequest,
    +}
    +
    +/// Represents the collection of Object Identifiers (OIDs) used in various cryptographic standards.
    +///
    +/// This enum provides a C-compatible representation of OIDs, which uniquely identify
    +/// algorithms and standards in cryptography. OIDs are used in multiple contexts, including
    +/// hashing algorithms, public key cryptography, encryption algorithms, key agreement protocols,
    +/// and certificate extensions.
    +///
    +/// # Examples
    +///
    +/// Using `ObjectIdentifiers` for RSA encryption:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::{ObjectIdentifiers, OidType};
    +///
    +/// let oid = ObjectIdentifiers::Oid(OidType::RsaEncryption);
    +/// ```
    +///
    +/// # Note
    +///
    +/// The `#[repr(C)]` attribute ensures C compatibility, facilitating the use of these enums
    +/// in systems where interoperability with C is required. OIDs play a crucial role in the
    +/// configuration and operation of cryptographic systems, ensuring the correct application
    +/// of algorithms and standards.
    +#[repr(C)]
    +pub enum ObjectIdentifiers {
    +    /// Container for various cryptographic Object Identifiers (OIDs).
    +    Oid(OidType),
    +}
    +
    +/// Enumerates specific Object Identifier (OID) types across cryptographic functionalities.
    +///
    +/// Lists OIDs for hashing algorithms, public key cryptography, encryption algorithms,
    +/// key agreement protocols, certificate extensions, extended key usage identifiers, and
    +/// other notable OIDs.
    +///
    +/// # Hashing Algorithms
    +/// - `Sha1WithRsaEncryption`, `Sha256WithRsaEncryption`, etc.
    +///
    +/// # Public Key Cryptography
    +/// - `RsaEncryption`, `EcPublicKey`, `EcdsaWithSha*`
    +///
    +/// # Encryption Algorithms
    +/// - `Aes128Cbc`, `Aes256Gcm`, etc.
    +///
    +/// # Key Agreement
    +/// - `DhPublicNumber`, `EcdhStandardCurves`
    +///
    +/// # Certificate Extensions
    +/// - `SubjectKeyIdentifier`, `ExtendedKeyUsage`, etc.
    +///
    +/// # Extended Key Usage OIDs
    +/// - `ServerAuth`, `ClientAuth`, `CodeSigning`, etc.
    +///
    +/// # Other notable OIDs
    +/// - `Pkix`, `Pkcs7Data`, `Pkcs9EmailAddress`, etc.
    +///
    +/// # Examples
    +///
    +/// Selecting an OID for AES 256 CBC encryption:
    +///
    +/// ```rust
    +/// use tpm_poc::common::crypto::pkcs::standards::OidType;
    +///
    +/// let oid_type = OidType::Aes256Cbc;
    +/// ```
    +///
    +/// # Note
    +///
    +/// Uses `#[repr(C)]` for C language compatibility. Understanding and using the correct OIDs
    +/// is essential for ensuring cryptographic operations adhere to the intended standards and
    +/// protocols.
    +#[repr(C)]
    +pub enum OidType {
    +    // Hashing Algorithms
    +    Sha1WithRsaEncryption,
    +    Sha256WithRsaEncryption,
    +    Sha384WithRsaEncryption,
    +    Sha512WithRsaEncryption,
    +    IdSha1,
    +    IdSha256,
    +    IdSha384,
    +    IdSha512,
    +
    +    // Public Key Cryptography
    +    RsaEncryption,
    +    IdRsaSsaPss,
    +    EcPublicKey,
    +    EcdsaWithSha1,
    +    EcdsaWithSha256,
    +    EcdsaWithSha384,
    +    EcdsaWithSha512,
    +
    +    // Encryption Algorithms
    +    Aes128Cbc,
    +    Aes192Cbc,
    +    Aes256Cbc,
    +    Aes128Gcm,
    +    Aes192Gcm,
    +    Aes256Gcm,
    +
    +    // Key Agreement
    +    DhPublicNumber,
    +    EcdhStandardCurves,
    +    EcdhSpecifiedCurves,
    +
    +    // Certificate Extensions
    +    SubjectKeyIdentifier,
    +    KeyUsage,
    +    SubjectAltName,
    +    BasicConstraints,
    +    ExtendedKeyUsage,
    +
    +    // Extended Key Usage OIDs
    +    ServerAuth,
    +    ClientAuth,
    +    CodeSigning,
    +    EmailProtection,
    +    TimeStamping,
    +    OcspSigning,
    +    DocumentSigning,
    +
    +    // Other OIDs
    +    Pkix,
    +    Pkcs7Data,
    +    Pkcs7SignedData,
    +    Pkcs7EnvelopedData,
    +    Pkcs7SignedAndEnvelopedData,
    +    Pkcs7DigestData,
    +    Pkcs7EncryptedData,
    +    Pkcs9EmailAddress,
    +    Pkcs9UnstructuredName,
    +    Pkcs9ContentType,
    +    Pkcs9MessageDigest,
    +    Pkcs9SigningTime,
    +}
    +
    +impl OidType {
    +    pub fn as_str(&self) -> &'static str {
    +        match self {
    +            OidType::Sha1WithRsaEncryption => "1.2.840.113549.1.1.5",
    +            OidType::Sha256WithRsaEncryption => "1.2.840.113549.1.1.11",
    +            OidType::Sha384WithRsaEncryption => "1.2.840.113549.1.1.12",
    +            OidType::Sha512WithRsaEncryption => "1.2.840.113549.1.1.13",
    +            OidType::IdSha1 => "1.3.14.3.2.26",
    +            OidType::IdSha256 => "2.16.840.1.101.3.4.2.1",
    +            OidType::IdSha384 => "2.16.840.1.101.3.4.2.2",
    +            OidType::IdSha512 => "2.16.840.1.101.3.4.2.3",
    +            OidType::RsaEncryption => "1.2.840.113549.1.1.1",
    +            OidType::IdRsaSsaPss => "1.2.840.113549.1.1.10",
    +            OidType::EcPublicKey => "1.2.840.10045.2.1",
    +            OidType::EcdsaWithSha1 => "1.2.840.10045.4.1",
    +            OidType::EcdsaWithSha256 => "1.2.840.10045.4.3.2",
    +            OidType::EcdsaWithSha384 => "1.2.840.10045.4.3.3",
    +            OidType::EcdsaWithSha512 => "1.2.840.10045.4.3.4",
    +            OidType::Aes128Cbc => "2.16.840.1.101.3.4.1.2",
    +            OidType::Aes192Cbc => "2.16.840.1.101.3.4.1.22",
    +            OidType::Aes256Cbc => "2.16.840.1.101.3.4.1.42",
    +            OidType::Aes128Gcm => "2.16.840.1.101.3.4.1.6",
    +            OidType::Aes192Gcm => "2.16.840.1.101.3.4.1.26",
    +            OidType::Aes256Gcm => "2.16.840.1.101.3.4.1.46",
    +            OidType::DhPublicNumber => "1.2.840.10046.2.1",
    +            OidType::EcdhStandardCurves => "1.3.132.0",
    +            OidType::EcdhSpecifiedCurves => "1.2.840.10045.3.1",
    +            OidType::SubjectKeyIdentifier => "2.5.29.14",
    +            OidType::KeyUsage => "2.5.29.15",
    +            OidType::SubjectAltName => "2.5.29.17",
    +            OidType::BasicConstraints => "2.5.29.19",
    +            OidType::ExtendedKeyUsage => "2.5.29.37",
    +            OidType::ServerAuth => "1.3.6.1.5.5.7.3.1",
    +            OidType::ClientAuth => "1.3.6.1.5.5.7.3.2",
    +            OidType::CodeSigning => "1.3.6.1.5.5.7.3.3",
    +            OidType::DocumentSigning => "1.3.6.1.4.1.311.10.3.12",
    +            OidType::EmailProtection => "1.3.6.1.5.5.7.3.4",
    +            OidType::TimeStamping => "1.3.6.1.5.5.7.3.8",
    +            OidType::OcspSigning => "1.3.6.1.5.5.7.3.9",
    +            OidType::Pkix => "1.3.6.1.5.5.7",
    +            OidType::Pkcs7Data => "1.2.840.113549.1.7.1",
    +            OidType::Pkcs7SignedData => "1.2.840.113549.1.7.2",
    +            OidType::Pkcs7EnvelopedData => "1.2.840.113549.1.7.3",
    +            OidType::Pkcs7SignedAndEnvelopedData => "1.2.840.113549.1.7.4",
    +            OidType::Pkcs7DigestData => "1.2.840.113549.1.7.5",
    +            OidType::Pkcs7EncryptedData => "1.2.840.113549.1.7.6",
    +            OidType::Pkcs9EmailAddress => "1.2.840.113549.1.9.1",
    +            OidType::Pkcs9UnstructuredName => "1.2.840.113549.1.9.2",
    +            OidType::Pkcs9ContentType => "1.2.840.113549.1.9.3",
    +            OidType::Pkcs9MessageDigest => "1.2.840.113549.1.9.4",
    +            OidType::Pkcs9SigningTime => "1.2.840.113549.1.9.5",
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/error.rs.html b/Documentation/RustDoc/src/crypto_layer/common/error.rs.html new file mode 100644 index 00000000..809681f4 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/error.rs.html @@ -0,0 +1,269 @@ +error.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +
    #[cfg(feature = "tpm")]
    +use crate::tpm::core::error::TpmError;
    +
    +#[cfg(feature = "hsm")]
    +use crate::hsm::core::error::HsmError;
    +use std::fmt;
    +
    +/// Represents errors that can occur within a security module.
    +///
    +/// This enum encapsulates various types of errors, including those originating
    +/// from a Hardware Security Module (HSM), a Trusted Platform Module (TPM), or during
    +/// the initialization process. It also includes errors related to cryptographic operations
    +/// such as signing, decryption, encryption, and signature verification.
    +#[derive(Debug)]
    +#[repr(C)]
    +pub enum SecurityModuleError {
    +    #[cfg(feature = "hsm")]
    +    /// Error originating from a Hardware Security Module (HSM).
    +    Hsm(HsmError),
    +    #[cfg(feature = "tpm")]
    +    /// Error originating from a Trusted Platform Module (TPM).
    +    Tpm(TpmError),
    +    /// Error that occurred during the signing operation.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    SigningError(String),
    +    /// Error that occurred during the decryption operation.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    DecryptionError(String),
    +    /// Error that occurred during the encryption operation.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    EncryptionError(String),
    +    /// Error that occurred during the signature verification operation.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    SignatureVerificationError(String),
    +    /// Error that occurs during the initialization process.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    InitializationError(String),
    +    /// Error that occurred during the key generation operation.
    +    ///
    +    /// This variant contains a descriptive error message.
    +    CreationError(String),
    +}
    +
    +impl fmt::Display for SecurityModuleError {
    +    /// Provides a human-readable description of the security module error.
    +    ///
    +    /// Formats the error message based on the error type, ensuring that it is
    +    /// descriptive and easy to understand.
    +    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    +        match *self {
    +            #[cfg(feature = "hsm")]
    +            SecurityModuleError::Hsm(ref err) => {
    +                write!(f, "HSM error: {}", err)
    +            }
    +            #[cfg(feature = "tpm")]
    +            SecurityModuleError::Tpm(ref err) => {
    +                write!(f, "TPM error: {}", err)
    +            }
    +            SecurityModuleError::SigningError(ref error_msg) => {
    +                write!(f, "Signing error: {}", error_msg)
    +            }
    +            SecurityModuleError::DecryptionError(ref error_msg) => {
    +                write!(f, "Decryption error: {}", error_msg)
    +            }
    +            SecurityModuleError::EncryptionError(ref error_msg) => {
    +                write!(f, "Encryption error: {}", error_msg)
    +            }
    +            SecurityModuleError::SignatureVerificationError(ref error_msg) => {
    +                write!(f, "Signature verification error: {}", error_msg)
    +            }
    +            SecurityModuleError::InitializationError(ref error_msg) => {
    +                write!(f, "Initialization error: {}", error_msg)
    +            }
    +            SecurityModuleError::CreationError(ref error_msg) => {
    +                write!(f, "Creation error: {}", error_msg)
    +            }
    +        }
    +    }
    +}
    +
    +impl std::error::Error for SecurityModuleError {
    +    /// Provides the source of the security module error, if available.
    +    ///
    +    /// This method helps in understanding and diagnosing the underlying cause of the error,
    +    /// particularly useful when debugging or logging error information.
    +    ///
    +    /// For errors originating from an HSM or TPM, the source error is returned.
    +    /// For other error variants, `None` is returned, as they do not have an underlying source error.
    +    #[tracing::instrument]
    +    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    +        match *self {
    +            #[cfg(feature = "hsm")]
    +            SecurityModuleError::Hsm(ref err) => Some(err),
    +            #[cfg(feature = "tpm")]
    +            SecurityModuleError::Tpm(ref err) => Some(err),
    +            SecurityModuleError::SigningError(_) => None,
    +            SecurityModuleError::DecryptionError(_) => None,
    +            SecurityModuleError::EncryptionError(_) => None,
    +            SecurityModuleError::SignatureVerificationError(_) => None,
    +            SecurityModuleError::InitializationError(_) => None,
    +            SecurityModuleError::CreationError(_) => None
    +        }
    +    }
    +}
    +
    +#[cfg(feature = "hsm")]
    +impl From<HsmError> for SecurityModuleError {
    +    /// Converts an `HsmError` into a `SecurityModuleError`.
    +    ///
    +    /// This conversion simplifies error handling by allowing direct use of `HsmError`
    +    /// values in contexts where `SecurityModuleError` is expected.
    +    #[tracing::instrument]
    +    fn from(err: HsmError) -> SecurityModuleError {
    +        SecurityModuleError::Hsm(err)
    +    }
    +}
    +
    +#[cfg(feature = "tpm")]
    +impl From<TpmError> for SecurityModuleError {
    +    /// Converts a `TpmError` into a `SecurityModuleError`.
    +    ///
    +    /// Similar to the conversion from `HsmError`, this allows for streamlined error
    +    /// handling and propagation of `TpmError` values as `SecurityModuleError`.
    +    #[tracing::instrument]
    +    fn from(err: TpmError) -> SecurityModuleError {
    +        SecurityModuleError::Tpm(err)
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/factory.rs.html b/Documentation/RustDoc/src/crypto_layer/common/factory.rs.html new file mode 100644 index 00000000..458e02c5 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/factory.rs.html @@ -0,0 +1,277 @@ +factory.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +
    use super::traits::{log_config::LogConfig, module_provider::Provider};
    +#[cfg(feature = "hsm")]
    +use crate::hsm::core::instance::{HsmInstance, HsmType};
    +#[cfg(feature = "tpm")]
    +use crate::tpm::core::instance::{TpmInstance, TpmType};
    +use once_cell::sync::Lazy;
    +use std::{
    +    collections::HashMap,
    +    sync::{Arc, Mutex},
    +};
    +
    +type ProviderArc = Arc<Mutex<dyn Provider>>;
    +type SecurityModuleMap = HashMap<SecurityModule, ProviderArc>;
    +type SecurityModuleInstances = Lazy<Mutex<SecurityModuleMap>>;
    +
    +/// Represents the available types of security modules in the system.
    +///
    +/// This enum categorizes security modules into HSM (Hardware Security Module) and
    +/// TPM (Trusted Platform Module), allowing for a unified interface when working with different types of security modules.
    +#[repr(C)]
    +#[derive(Eq, Hash, PartialEq, Clone, Debug)]
    +pub enum SecurityModule {
    +    #[cfg(feature = "hsm")]
    +    Hsm(HsmType),
    +    #[cfg(feature = "tpm")]
    +    Tpm(TpmType),
    +}
    +
    +/// Provides conversion from a string slice to a `SecurityModule` variant.
    +///
    +/// This implementation allows for easy instantiation of `SecurityModule` variants
    +/// from string identifiers, facilitating user or configuration-based module selection.
    +impl From<&str> for SecurityModule {
    +    fn from(item: &str) -> Self {
    +        match item {
    +            #[cfg(feature = "tpm")]
    +            "TPM" => SecurityModule::Tpm(TpmType::default()),
    +            #[cfg(feature = "hsm")]
    +            "HSM" => SecurityModule::Hsm(HsmType::default()),
    +            _ => panic!("Unsupported Security Module type"),
    +        }
    +    }
    +}
    +
    +/// A thread-safe, lazily-initialized global registry of security module instances.
    +///
    +/// This static variable holds a `Mutex`-protected `HashMap` that maps `SecurityModule`
    +/// variants to their corresponding provider instances. It ensures that module instances
    +/// are unique and accessible across the application.
    +static INSTANCES: SecurityModuleInstances = Lazy::new(|| Mutex::new(HashMap::new()));
    +static LOGGING_INITIALIZED: Mutex<bool> = Mutex::new(false);
    +
    +/// A container struct for security module-related functionality.
    +///
    +/// This struct serves as a namespace for functions related to security module instances,
    +/// such as retrieving and creating them.
    +#[repr(C)]
    +pub struct SecModules {}
    +
    +/// Provides methods related to managing and accessing security module instances.
    +impl SecModules {
    +    /// Retrieves or creates an instance of a security module based on the provided key and type.
    +    ///
    +    /// If an instance for the given module and key does not exist, it is created and stored.
    +    /// Otherwise, the existing instance is returned.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A `String` identifier for the security module instance.
    +    /// * `module` - The `SecurityModule` variant representing the type of module to retrieve or create.
    +    ///
    +    /// # Returns
    +    ///
    +    /// An `Option` containing an `Arc<Mutex<dyn Provider>>` to the requested module instance,
    +    /// or `None` if the module type is not supported or an error occurs during instance creation.
    +    pub fn get_instance(
    +        key_id: String,
    +        module: SecurityModule,
    +        log: Option<Box<dyn LogConfig>>,
    +    ) -> Option<Arc<Mutex<dyn Provider>>> {
    +        // Initialize logging once
    +        if !*LOGGING_INITIALIZED.lock().unwrap() {
    +            if let Some(log_inst) = log {
    +                log_inst.setup_logging();
    +            }
    +            *LOGGING_INITIALIZED.lock().unwrap() = true;
    +        }
    +
    +        // Check if requested instance is in cache. If not, create a new instance
    +        let mut instances = INSTANCES.lock().unwrap();
    +        if !instances.contains_key(&module) {
    +            let instance = SecModule::create_instance(key_id, &module);
    +            instances.insert(module.clone(), instance?);
    +        }
    +
    +        instances.get(&module).cloned()
    +    }
    +}
    +
    +/// Represents a specific instance of a security module.
    +///
    +/// This struct is used internally to manage individual instances of security modules,
    +/// encapsulating the module's type and the provider instance that handles its functionality.
    +#[repr(C)]
    +struct SecModule {
    +    name: String,
    +    instance: Arc<Mutex<dyn Provider>>,
    +}
    +
    +/// Encapsulates functionality for creating security module instances.
    +impl SecModule {
    +    /// Creates and returns an instance of a security module provider based on the module type.
    +    ///
    +    /// This function is responsible for instantiating providers for HSM and TPM modules.
    +    /// It delegates the instantiation to the specific module's implementation.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A `String` identifier for the security module instance.
    +    /// * `module` - A reference to the `SecurityModule` for which to create the instance.
    +    ///
    +    /// # Returns
    +    ///
    +    /// An `Arc<Mutex<dyn Provider>>` representing the created module instance,
    +    /// or `None` if the module type is not supported or an error occurs during instance creation.
    +    fn create_instance(
    +        key_id: String,
    +        module: &SecurityModule,
    +    ) -> Option<Arc<Mutex<dyn Provider>>> {
    +        match module {
    +            #[cfg(feature = "hsm")]
    +            SecurityModule::Hsm(hsm_type) => Some(HsmInstance::create_instance(key_id, hsm_type)),
    +            #[cfg(feature = "tpm")]
    +            SecurityModule::Tpm(tpm_type) => Some(TpmInstance::create_instance(key_id, tpm_type)),
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/common/mod.rs.html new file mode 100644 index 00000000..56ca4817 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/mod.rs.html @@ -0,0 +1,11 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +
    pub mod crypto;
    +pub mod error;
    +pub mod factory;
    +pub mod traits;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/traits/key_handle.rs.html b/Documentation/RustDoc/src/crypto_layer/common/traits/key_handle.rs.html new file mode 100644 index 00000000..db0c7484 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/traits/key_handle.rs.html @@ -0,0 +1,187 @@ +key_handle.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +
    use crate::common::error::SecurityModuleError;
    +use std::fmt::Debug;
    +#[cfg(feature = "linux")]
    +use tss_esapi::handles::KeyHandle as TssKeyHandle;
    +#[cfg(feature = "win")]
    +use windows::Win32::Security::Cryptography::NCRYPT_KEY_HANDLE;
    +
    +/// An enum representing a generic key handle that can be used on different platforms.
    +///
    +/// This enum provides a platform-agnostic way to handle cryptographic keys. It has two variants:
    +///
    +/// - `Linux`: Used on Linux platforms, wrapping the `TssKeyHandle` type from the `tss_esapi` crate.
    +/// - `Windows`: Used on Windows platforms, wrapping the `NCRYPT_KEY_HANDLE` type from the `windows` crate.
    +///
    +/// By using this enum, you can write code that works with cryptographic keys on both Linux and Windows platforms
    +/// without having to worry about the underlying platform-specific types.
    +#[repr(C)]
    +#[cfg(any(feature = "linux", feature = "win"))]
    +pub enum GenericKeyHandle {
    +    #[cfg(feature = "linux")]
    +    Linux(TssKeyHandle),
    +    #[cfg(feature = "win")]
    +    Windows(NCRYPT_KEY_HANDLE),
    +}
    +
    +/// Defines a common interface for cryptographic key operations.
    +///
    +/// This trait specifies methods for key operations such as signing data, encrypting,
    +/// decrypting, and verifying signatures. It's designed to be implemented by security
    +/// modules that manage cryptographic keys, ensuring a consistent interface for key
    +/// operations across different types of security modules. Implementors of this trait
    +/// must ensure thread safety.
    +pub trait KeyHandle: Send + Sync + Debug {
    +    /// Signs the given data using the cryptographic key.
    +    ///
    +    /// # Arguments
    +    /// * `data` - A byte slice representing the data to be signed.
    +    ///
    +    /// # Returns
    +    /// A `Result` containing the signature as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[tracing::instrument]
    +    fn sign_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        Err(SecurityModuleError::InitializationError(
    +            "Method not implemented".to_owned(),
    +        ))
    +    }
    +    /// Decrypts the given encrypted data using the cryptographic key.
    +    ///
    +    /// # Arguments
    +    /// * `encrypted_data` - A byte slice representing the data to be decrypted.
    +    ///
    +    /// # Returns
    +    /// A `Result` containing the decrypted data as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[tracing::instrument]
    +    fn decrypt_data(&self, _encrypted_data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        Err(SecurityModuleError::InitializationError(
    +            "Method not implemented".to_owned(),
    +        ))
    +    }
    +    /// Encrypts the given data using the cryptographic key.
    +    ///
    +    /// # Arguments
    +    /// * `data` - A byte slice representing the data to be encrypted.
    +    ///
    +    /// # Returns
    +    /// A `Result` containing the encrypted data as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[tracing::instrument]
    +    fn encrypt_data(&self, _data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        Err(SecurityModuleError::InitializationError(
    +            "Method not implemented".to_owned(),
    +        ))
    +    }
    +    /// Verifies the signature of the given data using the cryptographic key.
    +    ///
    +    /// # Arguments
    +    /// * `data` - A byte slice representing the data whose signature is to be verified.
    +    /// * `signature` - A byte slice representing the signature to be verified against the data.
    +    ///
    +    /// # Returns
    +    /// A `Result` containing a boolean indicating whether the signature is valid (`true`) or not (`false`),
    +    /// or a `SecurityModuleError` on failure.
    +    #[tracing::instrument]
    +    fn verify_signature(
    +        &self,
    +        _data: &[u8],
    +        _signature: &[u8],
    +    ) -> Result<bool, SecurityModuleError> {
    +        Err(SecurityModuleError::InitializationError(
    +            "Method not implemented".to_owned(),
    +        ))
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/traits/log_config.rs.html b/Documentation/RustDoc/src/crypto_layer/common/traits/log_config.rs.html new file mode 100644 index 00000000..7ed75df6 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/traits/log_config.rs.html @@ -0,0 +1,37 @@ +log_config.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +
    use std::{any::Any, fmt::Debug};
    +
    +/// Defines the interface for configuration data used by the `Provider` trait methods.
    +///
    +/// This trait allows for dynamic configuration structures to be passed to methods
    +/// like `create_key` and `load_key`. It enables the `Provider` implementations to
    +/// handle various types of configurations in a type-safe manner.
    +///
    +/// The `Config` trait ensures that configuration data can be dynamically cast to the
    +/// appropriate type needed by the `Provider` implementation. This is done through
    +/// the `as_any` method, which provides a way to perform dynamic downcasting.
    +///
    +/// Implementors of this trait must also implement the `Debug` trait to provide
    +/// debugging information and the `Any` trait to support type-safe downcasting.
    +pub trait LogConfig: Any + Debug {
    +    fn setup_logging(&self);
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/traits/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/common/traits/mod.rs.html new file mode 100644 index 00000000..dccbc22b --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/traits/mod.rs.html @@ -0,0 +1,11 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +
    pub mod key_handle;
    +pub mod module_provider;
    +pub mod module_provider_config;
    +pub mod log_config;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider.rs.html b/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider.rs.html new file mode 100644 index 00000000..61d169ff --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider.rs.html @@ -0,0 +1,119 @@ +module_provider.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +
    use super::key_handle::KeyHandle;
    +use crate::common::error::SecurityModuleError;
    +use std::{any::Any, fmt::Debug};
    +
    +/// Defines the interface for a security module provider.
    +///
    +/// This trait encapsulates operations related to cryptographic processing, such as
    +/// data encryption/decryption and signing/verification, as well as key management through
    +/// a `ProviderHandle`. It ensures a unified approach to interacting with different types
    +/// of security modules.
    +///
    +/// Implementors of this trait must also implement the `KeyHandle` trait to provide
    +/// cryptographic key operations.
    +pub trait Provider: Send + Sync + KeyHandle + Debug {
    +    /// Creates a new cryptographic key identified by `key_id`.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A string slice that uniquely identifies the key to be created.
    +    /// * `key_algorithm` - The asymmetric encryption algorithm to be used for the key.
    +    /// * `sym_algorithm` - An optional symmetric encryption algorithm to be used with the key.
    +    /// * `hash` - An optional hash algorithm to be used with the key.
    +    /// * `key_usages` - A vector of `AppKeyUsage` values specifying the intended usages for the key.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` that, on success, contains `Ok(())`, indicating that the key was created successfully.
    +    /// On failure, it returns a `SecurityModuleError`.
    +    fn create_key(&mut self, key_id: &str, config: Box<dyn Any>)
    +        -> Result<(), SecurityModuleError>;
    +
    +    /// Loads an existing cryptographic key identified by `key_id`.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A string slice that uniquely identifies the key to be loaded.
    +    /// * `key_algorithm` - The asymmetric encryption algorithm used for the key.
    +    /// * `sym_algorithm` - An optional symmetric encryption algorithm used with the key.
    +    /// * `hash` - An optional hash algorithm used with the key.
    +    /// * `key_usages` - A vector of `AppKeyUsage` values specifying the intended usages for the key.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` that, on success, contains `Ok(())`, indicating that the key was loaded successfully.
    +    /// On failure, it returns a `SecurityModuleError`.
    +    fn load_key(&mut self, key_id: &str, config: Box<dyn Any>) -> Result<(), SecurityModuleError>;
    +
    +    /// Initializes the security module and returns a handle for further operations.
    +    ///
    +    /// This method should be called before performing any other operations with the security module.
    +    /// It initializes the module and prepares it for use.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` that, on success, contains `Ok(())`, indicating that the module was initialized successfully.
    +    /// On failure, it returns a `SecurityModuleError`.
    +    fn initialize_module(&mut self) -> Result<(), SecurityModuleError>;
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider_config.rs.html b/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider_config.rs.html new file mode 100644 index 00000000..a594798a --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/common/traits/module_provider_config.rs.html @@ -0,0 +1,53 @@ +module_provider_config.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +
    use std::{any::Any, fmt::Debug};
    +
    +/// Defines the interface for configuration data used by the `Provider` trait methods.
    +///
    +/// This trait allows for dynamic configuration structures to be passed to methods
    +/// like `create_key` and `load_key`. It enables the `Provider` implementations to
    +/// handle various types of configurations in a type-safe manner.
    +///
    +/// The `Config` trait ensures that configuration data can be dynamically cast to the
    +/// appropriate type needed by the `Provider` implementation. This is done through
    +/// the `as_any` method, which provides a way to perform dynamic downcasting.
    +///
    +/// Implementors of this trait must also implement the `Debug` trait to provide
    +/// debugging information and the `Any` trait to support type-safe downcasting.
    +pub trait ProviderConfig: Any + Debug {
    +    /// Returns a reference to the underlying `Any` type.
    +    ///
    +    /// This method allows for downcasting the `Config` trait object to its concrete type.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A reference to the `Any` trait object, which can then be downcast to the
    +    /// specific type implementing `Config`.
    +    fn as_any(&self) -> &dyn Any;
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/lib.rs.html b/Documentation/RustDoc/src/crypto_layer/lib.rs.html new file mode 100644 index 00000000..aa091a96 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/lib.rs.html @@ -0,0 +1,29 @@ +lib.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +
    pub mod common;
    +#[cfg(feature = "ffi")]
    +pub mod ffi;
    +#[cfg(feature = "hsm")]
    +pub mod hsm;
    +#[cfg(test)]
    +mod tests;
    +#[cfg(feature = "tpm")]
    +pub mod tpm;
    +
    +pub use common::{error::SecurityModuleError, factory::SecModules};
    +#[cfg(feature = "ffi")]
    +pub use ffi::factory::{secmodules_free_instance, secmodules_get_instance};
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/android_logger.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/android_logger.rs.html new file mode 100644 index 00000000..4ee74c96 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/android_logger.rs.html @@ -0,0 +1,31 @@ +android_logger.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +
    use tracing_subscriber::{layer::SubscriberExt, Registry};
    +
    +use crate::common::traits::log_config::LogConfig;
    +
    +#[derive(Debug)]
    +pub struct DefaultAndroidLogger;
    +
    +impl LogConfig for DefaultAndroidLogger {
    +    fn setup_logging(&self) {
    +        let subscriber = Registry::default().with(tracing_android::layer("RUST").unwrap());
    +        tracing::subscriber::set_global_default(subscriber)
    +            .expect("setting default subscriber failed");
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/config.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/config.rs.html new file mode 100644 index 00000000..d2e3a4e7 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/config.rs.html @@ -0,0 +1,91 @@ +config.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +
    use std::any::Any;
    +
    +use robusta_jni::jni::JavaVM;
    +
    +use crate::common::{
    +    crypto::{
    +        algorithms::encryption::{AsymmetricEncryption, BlockCiphers},
    +        algorithms::hashes::Hash,
    +        KeyUsage,
    +    },
    +    traits::module_provider_config::ProviderConfig,
    +};
    +
    +#[derive(Debug, Clone, Copy)]
    +pub enum EncryptionMode {
    +    Sym(BlockCiphers),
    +    ASym {
    +        algo: AsymmetricEncryption,
    +        digest: Hash,
    +    },
    +}
    +
    +pub struct AndroidConfig {
    +    pub mode: EncryptionMode,
    +    pub key_usages: Vec<KeyUsage>,
    +    pub hardware_backed: bool,
    +    pub vm: Option<JavaVM>,
    +}
    +
    +impl std::fmt::Debug for AndroidConfig {
    +    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    +        f.debug_struct("AndroidProvider")
    +            .field("mode", &self.mode)
    +            .field("key_usages", &self.key_usages)
    +            .field("hardware_backed", &self.hardware_backed)
    +            .finish()
    +    }
    +}
    +
    +impl ProviderConfig for AndroidConfig {
    +    fn as_any(&self) -> &dyn Any {
    +        self
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/error.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/error.rs.html new file mode 100644 index 00000000..a4f83091 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/error.rs.html @@ -0,0 +1,127 @@ +error.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +
    use crate::tpm::core::error::{ToTpmError, TpmError};
    +
    +use super::wrapper;
    +
    +#[derive(Debug)]
    +pub(crate) struct JavaException(String);
    +
    +impl std::fmt::Display for JavaException {
    +    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    +        write!(f, "Java Exception: {}", self.0)
    +    }
    +}
    +
    +impl std::error::Error for JavaException {}
    +
    +/// This allows converting the JNI result into a `TpmError` result.
    +impl<T> ToTpmError<T> for robusta_jni::jni::errors::Result<T> {
    +    /// Converts the JNI result into a `TpmError` result.
    +    /// If a Java exception was thrown, it retrieves the exception message and puts it into the error.
    +    /// If no exception was thrown, it returns the JNI error as the `TpmError`.
    +    fn err_internal(self) -> Result<T, TpmError> {
    +        match self {
    +            Ok(v) => Ok(v),
    +            Err(e) => {
    +                // check if a java exception was thrown
    +                let vm =
    +                    wrapper::get_java_vm().map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +                let env = vm
    +                    .get_env()
    +                    .map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +                if env
    +                    .exception_check()
    +                    .map_err(|e| TpmError::InternalError(Box::new(e)))?
    +                {
    +                    // get the exception message and put it into the error
    +                    env.exception_describe()
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +                    let ex = env
    +                        .exception_occurred()
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +                    env.exception_clear()
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +                    let message = env
    +                        .call_method(ex, "getMessage", "()Ljava/lang/String;", &[])
    +                        .and_then(|v| v.l())
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?;
    +
    +                    let message = env
    +                        .get_string(Into::into(message))
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?
    +                        .to_str()
    +                        .map_err(|e| TpmError::InternalError(Box::new(e)))?
    +                        .to_string();
    +                    Err(TpmError::InternalError(Box::new(JavaException(message))))
    +                } else {
    +                    // there was no exception, return the jni error
    +                    Err(TpmError::InternalError(Box::new(e)))
    +                }
    +            }
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/interface.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/interface.rs.html new file mode 100644 index 00000000..86ef518e --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/interface.rs.html @@ -0,0 +1,734 @@ +interface.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +197
    +198
    +199
    +200
    +201
    +202
    +203
    +204
    +205
    +206
    +207
    +208
    +209
    +210
    +211
    +212
    +213
    +214
    +215
    +216
    +217
    +218
    +219
    +220
    +221
    +222
    +223
    +224
    +225
    +226
    +227
    +228
    +229
    +230
    +231
    +232
    +233
    +234
    +235
    +236
    +237
    +238
    +239
    +240
    +241
    +242
    +243
    +244
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    +254
    +255
    +256
    +257
    +258
    +259
    +260
    +261
    +262
    +263
    +264
    +265
    +266
    +267
    +268
    +269
    +270
    +271
    +272
    +273
    +274
    +275
    +276
    +277
    +278
    +279
    +280
    +281
    +282
    +283
    +284
    +285
    +286
    +287
    +288
    +289
    +290
    +291
    +292
    +293
    +294
    +295
    +296
    +297
    +298
    +299
    +300
    +301
    +302
    +303
    +304
    +305
    +306
    +307
    +308
    +309
    +310
    +311
    +312
    +313
    +314
    +315
    +316
    +317
    +318
    +319
    +320
    +321
    +322
    +323
    +324
    +325
    +326
    +327
    +328
    +329
    +330
    +331
    +332
    +333
    +334
    +335
    +336
    +337
    +338
    +339
    +340
    +341
    +342
    +343
    +344
    +345
    +346
    +347
    +348
    +349
    +350
    +351
    +352
    +353
    +354
    +355
    +356
    +357
    +358
    +359
    +360
    +361
    +362
    +363
    +364
    +365
    +366
    +
    use robusta_jni::bridge;
    +
    +
    +#[bridge]
    +pub mod jni {
    +    #[allow(unused_imports)] //the bridge import is marked as unused, but if removed the compiler throws an error
    +    use robusta_jni::{
    +        bridge,
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Error,
    +            JNIEnv,
    +            objects::{
    +                AutoLocal,
    +                JValue
    +            },
    +            sys::jbyteArray
    +        },
    +    };
    +
    +    use crate::SecurityModuleError;
    +
    +    const CLASS_SIGNATURE: &str = "com/example/vulcans_limes/RustDef";
    +
    +    /// Contains all methods related to Rust - Java communication and the JNI
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(com.example.vulcans_1limes)]  //the 1 after the "_" is an escape character for the "_"
    +    pub struct RustDef<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +
    +    /// This Implementation provides the method declarations that are the interface for the JNI.
    +    /// The first part contains Java-methods that can be called from Rust.
    +    /// The second part contains some utility methods.
    +    ///
    +    /// All method signatures have to correspond to their counterparts in RustDef.java, with the
    +    /// same method name and corresponding parameters according to this table:
    +    /// | **Rust**                                           | **Java**                          |
    +    /// |----------------------------------------------------|-----------------------------------|
    +    /// | i32                                                | int                               |
    +    /// | bool                                               | boolean                           |
    +    /// | char                                               | char                              |
    +    /// | i8                                                 | byte                              |
    +    /// | f32                                                | float                             |
    +    /// | f64                                                | double                            |
    +    /// | i64                                                | long                              |
    +    /// | i16                                                | short                             |
    +    /// | String                                             | String                            |
    +    /// | Vec\<T\>                                           | ArrayList\<T\>                    |
    +    /// | Box\<[u8]\>                                        | byte[]                            |
    +    /// | [jni::JObject<'env>](jni::objects::JObject)        | *(any Java object as input type)* |
    +    /// | [jni::jobject](jni::sys::jobject)                  | *(any Java object as output)*     |
    +    /// |----------------------------------------------------------------------------------------|
    +    #[allow(non_snake_case)]
    +    impl<'env: 'borrow, 'borrow> RustDef<'env, 'borrow> {
    +        //------------------------------------------------------------------------------------------
    +        // Java methods that can be called from rust
    +
    +        ///Proof of concept method - shows call from Rust to a java method
    +        /// in order to find the signatures of the class and method, use
    +        /// `javap -s -p file/path/to/compiled/java/class`
    +        ///
    +        ///  DO NOT USE THIS METHOD
    +        #[allow(dead_code)]
    +        fn callback(environment: &JNIEnv) -> () {
    +            //This calls a method in Java in the Class RustDef, with the method name "callback"
    +            //and no arguments
    +            environment.call_static_method(
    +                CLASS_SIGNATURE, //Class signature
    +                "callback", //method name signature
    +                "()V", //parameter types of the method
    +                &[], //parameters to be passed to the method
    +            ).expect("Java func call failed");
    +        }
    +
    +        /// Creates a new cryptographic key identified by `key_id`.
    +        ///
    +        /// This method generates a new cryptographic key within the TPM.
    +        /// The key is made persistent and associated with the provided `key_id`.
    +        ///
    +        /// # Arguments
    +        /// `key_id` - String that uniquely identifies the key so that it can be retrieved later
    +        ///
    +        /// `key_gen_info` - A string that contains all relevant parameters for the key. Expected format depends on the algorithm:
    +        ///
    +        ///  RSA: "KEY_ALGORITHM;KEY_SIZE;HASH;PADDING",
    +        ///
    +        ///  EC: "KEY_ALGORITHM;CURVE;HASH"
    +        ///
    +        ///  AES + DES: KEY_ALGORITHM;KEY_SIZE;BLOCK_MODE;PADDING"
    +        pub fn create_key(environment: &JNIEnv, key_id: String, key_gen_info: String) -> Result<(), SecurityModuleError> {
    +            RustDef::initialize_module(environment)?;
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "create_key",
    +                "(Ljava/lang/String;Ljava/lang/String;)V",
    +                &[JValue::from(environment.new_string(key_id).unwrap()),
    +                  JValue::from(environment.new_string(key_gen_info).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(_) => Ok(()),
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to create key: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to create key: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +        /// Loads an existing cryptographic key identified by `key_id`.
    +        /// This key can then be used for cryptographic operations such as encryption or signing.
    +        ///
    +        /// # Arguments
    +        /// `key_id` - String that uniquely identifies the key so that it can be retrieved later
    +        pub fn load_key(environment: &JNIEnv, key_id: String) -> Result<(), SecurityModuleError> {
    +            RustDef::initialize_module(environment)?;
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "load_key",
    +                "(Ljava/lang/String;)V",
    +                &[JValue::from(environment.new_string(key_id).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(_) => Ok(()),
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to load key: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to load key: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +
    +        /// Initializes the TPM module.
    +        ///
    +        /// This method initializes the TPM context and prepares it for use. It should be called
    +        /// before performing any other operations with the TPM.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A `Result` that, on success, contains `()`,
    +        /// indicating that the module was initialized successfully.
    +        /// On failure, it returns an Error
    +        pub fn initialize_module(environment: &JNIEnv)
    +                                 -> Result<(), SecurityModuleError> {
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "initialize_module",
    +                "()V",
    +                &[],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(_) => Ok(()),
    +                Err(Error::JavaException) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to initialise Module: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::InitializationError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +        /// Signs the given data using the cryptographic key managed by the TPM provider.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `data` - A byte slice representing the data to be signed.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A `Result` containing the signature as a `Vec<u8>` on success,
    +        /// or an `Error` on failure.
    +        pub fn sign_data(environment: &JNIEnv, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "sign_data",
    +                "([B)[B",
    +                &[JValue::from(environment.byte_array_from_slice(data).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(value) => {
    +                    let vector = Self::convert_to_Vec_u8(environment, value);
    +                    match vector {
    +                        Ok(v) => Ok(v),
    +                        Err(_) => Err(SecurityModuleError::SigningError(
    +                            String::from("Failed to convert return type to rust-compatible format"))),
    +                    }
    +                },
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::SigningError(
    +                    String::from("Failed to sign data: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::SigningError(
    +                    String::from("Failed to sign data: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::SigningError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +        /// Verifies the signature of the given data using the key managed by the TPM
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `data` - A byte slice representing the data whose signature is to be verified
    +        /// * `signature` - A byte slice representing the signature to be verified.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A `Result` containing a `bool` signifying whether the signature is valid,
    +        /// or an `Error` on failure to determine the validity.
    +        pub fn verify_signature(environment: &JNIEnv, data: &[u8], signature: &[u8]) -> Result<bool, SecurityModuleError> {
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "verify_signature",
    +                "([B[B)Z",
    +                &[JValue::from(environment.byte_array_from_slice(data).unwrap()),
    +                    JValue::from(environment.byte_array_from_slice(signature).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(res) => match res.z() {
    +                    Ok(value) => Ok(value),
    +                    Err(_) => Err(SecurityModuleError::SignatureVerificationError(
    +                        String::from("Failed to convert return type to rust-compatible format"))),
    +                },
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::SignatureVerificationError(
    +                    String::from("Failed to verify signature: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::SignatureVerificationError(
    +                    String::from("Failed to verify signature: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::SignatureVerificationError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +        /// Encrypts the given data using the key managed by the TPM
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `data` - A byte slice representing the data to be encrypted.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A `Result` containing the encrypted data as a `Vec<u8>` on success,
    +        /// or an `Error` on failure.
    +        pub fn encrypt_data(environment: &JNIEnv, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "encrypt_data",
    +                "([B)[B",
    +                &[JValue::from(environment.byte_array_from_slice(data).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(value) => {
    +                    let vector = Self::convert_to_Vec_u8(environment, value);
    +                    match vector {
    +                        Ok(v) => Ok(v),
    +                        Err(_) => Err(SecurityModuleError::EncryptionError(
    +                            String::from("Failed to convert return type to rust-compatible format"))),
    +                    }
    +                },
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::EncryptionError(
    +                    String::from("Failed to encrypt data: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::EncryptionError(
    +                    String::from("Failed to encrypt data: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::EncryptionError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +
    +        /// Decrypts the given data using the key managed by the TPM
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `data` - A byte slice representing the data to be Decrypted.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A `Result` containing the Decrypted data as a `Vec<u8>` on success,
    +        /// or an `Error` on failure.
    +        pub fn decrypt_data(environment: &JNIEnv, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +            let result = environment.call_static_method(
    +                CLASS_SIGNATURE,
    +                "decrypt_data",
    +                "([B)[B",
    +                &[JValue::from(environment.byte_array_from_slice(data).unwrap())],
    +            );
    +            let _ = Self::check_java_exceptions(&environment);
    +            return match result {
    +                Ok(value) => {
    +                    let vector = Self::convert_to_Vec_u8(environment, value);
    +                    match vector {
    +                        Ok(v) => Ok(v),
    +                        Err(_) => Err(SecurityModuleError::DecryptionError(
    +                            String::from("Failed to convert return type to rust-compatible format"))),
    +                    }
    +                },
    +                Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::DecryptionError(
    +                    String::from("Failed to decrypt data: Wrong Arguments passed"))),
    +                Err(Error::JavaException) => Err(SecurityModuleError::DecryptionError(
    +                    String::from("Failed to decrypt data: Some exception occurred in Java. Check console for details"))),
    +                Err(_) => Err(SecurityModuleError::DecryptionError(
    +                    String::from("Failed to call Java methods"))),
    +            };
    +        }
    +
    +        //------------------------------------------------------------------------------------------
    +        // Utility Functions that are only used by other Rust functions.
    +        // These functions have no relation to RustDef.java
    +
    +        /// Converts a `JValue` representing a Java byte array (`jbyteArray`) to a Rust `Vec<u8>`.
    +        ///
    +        /// # Parameters
    +        /// - `environment`: A reference to the JNI environment. This is required for JNI operations.
    +        /// - `result`: The `JValue` that is expected to be a `jbyteArray`.
    +        ///
    +        /// # Returns
    +        /// - `Ok(Vec<u8>)` if the conversion is successful.
    +        /// - `Err(String)` if there is an error during the conversion process, with a description of the error.
    +        ///
    +        /// # Errors
    +        /// This method can fail in the following cases:
    +        /// - If there is a pending Java exception. In this case, an appropriate error message is returned.
    +        /// - If the `JValue` cannot be converted to a `Vec<u8>`.
    +        /// # Safety
    +        /// Ensure that the `JValue` passed is indeed a `jbyteArray` to avoid undefined behavior or unexpected errors.
    +        fn convert_to_Vec_u8(environment: &JNIEnv, result: JValue) -> Result<Vec<u8>, String> {
    +            Self::check_java_exceptions(environment)?;
    +            let jobj = result
    +                .l()
    +                .map_err(|_| String::from("Type conversion from JValue to JObject failed"))?
    +                .into_inner() as jbyteArray;
    +
    +            let output_vec = environment
    +                .convert_byte_array(jobj)
    +                .map_err(|_| String::from("Conversion from jbyteArray to Vec<u8> failed"))?;
    +            Self::check_java_exceptions(environment)?;
    +            Ok(output_vec)
    +        }
    +
    +        /// Checks for any pending Java exceptions in the provided Java environment (`JNIEnv`).
    +        /// If one is detected, it is printed to console and cleared so the program doesn't crash.
    +        /// # Arguments
    +        /// * `environment` - A reference to the Java environment (`JNIEnv`)
    +        /// # Returns
    +        /// * `Result<(), String>` - A Result type representing either success (if no exceptions
    +        ///                            are found) or an error (if exceptions are found).
    +        /// # Errors
    +        /// This method may return an error of type `JniError` if:
    +        /// * Any pending Java exceptions are found in the provided Java environment.
    +        pub fn check_java_exceptions(environment: &JNIEnv) -> Result<(), String> {
    +            if environment.exception_check().unwrap_or(true) {
    +                let _ = environment.exception_describe();
    +                let _ = environment.exception_clear();
    +                return Err(String::from("A Java exception occurred, check console for details"));
    +            } else {
    +                Ok(())
    +            }
    +        }
    +    }
    +}
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/key_handle.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/key_handle.rs.html new file mode 100644 index 00000000..3d6e0012 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/key_handle.rs.html @@ -0,0 +1,167 @@ +key_handle.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +
    use tracing::instrument;
    +
    +use crate::{
    +    common::{error::SecurityModuleError, traits::key_handle::KeyHandle},
    +    tpm::android::knox::interface::jni::RustDef
    +};
    +
    +use super::KnoxProvider;
    +
    +/// Implements the `Provider` trait, providing cryptographic operations
    +/// such as signing, encryption, decryption, and signature verification for the TPM Knox Vault.
    +///
    +/// This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations
    +/// In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault
    +impl KeyHandle for KnoxProvider {
    +    /// Signs data using the previously loaded cryptographic key.
    +    ///
    +    /// This method hashes the input data using SHA-256 and then signs the hash.
    +    /// The algorithm used for signing is determined by the currently loaded key.
    +    /// If no key is loaded, an Error is returned.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `data` - The data to be signed.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` containing the signature as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[instrument]
    +    fn sign_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        RustDef::sign_data(&self.get_env()?, data)
    +    }
    +
    +    /// Decrypts the data with the currently loaded key.
    +    /// The algorithm used for decryption is determined by the currently loaded key.
    +    /// If no key is loaded, an Error is returned.
    +    /// # Arguments
    +    ///
    +    /// * `encrypted_data` - The data to be decrypted.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` containing the decrypted data as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[instrument]
    +    fn decrypt_data(&self, encrypted_data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        RustDef::decrypt_data(&self.get_env()?, encrypted_data)
    +    }
    +
    +    /// Encrypts the data with the currently loaded key.
    +    /// The algorithm used for Encryption is determined by the currently loaded key.
    +    /// If no key is loaded, an Error is returned.
    +    /// # Arguments
    +    ///
    +    /// * `data` - The data to be encrypted.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` containing the encrypted data as a `Vec<u8>` on success, or a `SecurityModuleError` on failure.
    +    #[instrument]
    +    fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        RustDef::encrypt_data(&self.get_env()?, data)
    +    }
    +
    +    /// Verifies a signature against the provided data.
    +    ///
    +    /// This method hashes the input data using SHA-256 and then verifies the signature with the currently loaded key.
    +    /// The algorithm used for verification is determined by the currently loaded key.
    +    /// If no key is loaded, an Error is returned.
    +    /// # Arguments
    +    ///
    +    /// * `data` - The original data associated with the signature.
    +    /// * `signature` - The signature to be verified.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` indicating whether the signature is valid (`true`) or not (`false`),
    +    /// or a `SecurityModuleError` on failure.
    +    #[instrument]
    +    fn verify_signature(&self, data: &[u8], signature: &[u8]) -> Result<bool, SecurityModuleError> {
    +        RustDef::verify_signature(&self.get_env()?, data, signature)
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/mod.rs.html new file mode 100644 index 00000000..5f17494c --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/mod.rs.html @@ -0,0 +1,260 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +
    use std::any::Any;
    +use std::fmt;
    +use std::fmt::{Debug, Formatter};
    +
    +use robusta_jni::jni::{JavaVM, JNIEnv};
    +use tracing::instrument;
    +
    +use crate::common::crypto::algorithms::encryption::{AsymmetricEncryption, BlockCiphers};
    +use crate::common::traits::module_provider_config::ProviderConfig;
    +use crate::SecurityModuleError;
    +
    +mod interface;
    +pub mod key_handle;
    +pub mod provider;
    +
    +/// A TPM-based cryptographic provider for managing cryptographic keys and performing
    +/// cryptographic operations in a Samsung environment. This provider uses the Java Native Interface
    +/// and the Android Keystore API to access the TPM "Knox Vault" developed by Samsung. In theory,
    +/// this code should also work for other TPMs on Android Devices, though it is only tested with Knox Vault
    +#[repr(C)]
    +pub struct KnoxProvider {
    +    config: Option<KnoxConfig>,
    +}
    +
    +///implements the Debug trait for KnoxProvider to facilitate logging
    +impl Debug for KnoxProvider {
    +    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    +        f.debug_struct("KnoxProvider")
    +            .field("config", &self.config)
    +            .finish()
    +    }
    +}
    +
    +///Provides functions to manage the KnoxProvider and the stored values within
    +impl KnoxProvider {
    +    /// Constructs a new `TpmProvider`.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A new empty instance of `TpmProvider`.
    +    #[instrument]
    +    pub fn new() -> Self {
    +        Self { config: None }
    +    }
    +
    +    /// Sets the configuration for the `Knox` instance.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `config` - A `KnoxConfig` instance that contains the configuration settings.
    +    fn set_config(&mut self, config: KnoxConfig) -> () {
    +        self.config = Some(config);
    +    }
    +
    +    ///Get the JavaVM stored in &self and provides the JNIEnv based on it
    +    /// # Returns
    +    ///
    +    /// a JNIEnv on success to be used for JNI method calls.
    +    /// If the KnoxConfig has not been loaded yet or contains an invalid JavaVM, an error is returned
    +    fn get_env(&self) -> Result<JNIEnv, SecurityModuleError> {
    +        if self.config.is_none() { return Err(SecurityModuleError::InitializationError(String::from("No key loaded"))); }
    +        let conf = self.config
    +            .as_ref()
    +            .ok_or(
    +                SecurityModuleError::InitializationError(String::from("failed to store config data")))?;
    +        conf.vm
    +            .get_env()
    +            .map_err(|_| SecurityModuleError::InitializationError(String::from("failed to retrieve JNIEnv")))
    +    }
    +
    +    ///Converts the config parameter to a KnoxConfig
    +    fn downcast_config(config: Box<dyn Any>) -> Result<KnoxConfig, SecurityModuleError> {
    +        Ok(*config
    +            .downcast::<KnoxConfig>()
    +            .map_err(|err| SecurityModuleError::InitializationError(format!("wrong config provided: {:?}", err)))?)
    +    }
    +}
    +
    +/// A struct defining the needed values for the create_key() and load_key() functions
    +/// At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both.
    +/// For hashing operations, SHA-256 is always used since it is the only one available on Knox Vault
    +/// The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI
    +pub struct KnoxConfig {
    +    pub key_algorithm: Option<AsymmetricEncryption>,
    +    pub sym_algorithm: Option<BlockCiphers>,
    +    pub vm: JavaVM,
    +}
    +
    +/// implements the debug trait for KnoxConfig for logging
    +impl Debug for KnoxConfig {
    +    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    +        f.debug_struct("KnoxConfig")
    +            .field("key_algorithm", &self.key_algorithm)
    +            .field("sym_algorithm", &self.sym_algorithm)
    +            .field("JavaVM", &"Contains a JavaVM to interact with Java")
    +            .finish()
    +    }
    +}
    +
    +///implements ProviderConfig for KnoxConfig
    +impl ProviderConfig for KnoxConfig {
    +    fn as_any(&self) -> &dyn Any {
    +        self
    +    }
    +}
    +
    +/// Implements KnoxConfig and provides a constructor
    +impl KnoxConfig {
    +    /// creates a new KnoxConfig
    +    /// At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both.
    +    /// Otherwise, load_key() or create_key() will return an Error.
    +    /// The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI
    +    pub fn new(
    +        key_algorithm: Option<AsymmetricEncryption>,
    +        sym_algorithm: Option<BlockCiphers>,
    +        vm: JavaVM,
    +    ) -> Result<KnoxConfig, SecurityModuleError> {
    +        if (key_algorithm.is_none() && sym_algorithm.is_none()) ||
    +            (key_algorithm.is_some() && sym_algorithm.is_some()) {
    +            return Err(SecurityModuleError::InitializationError(
    +                String::from("Either sym_algorithm OR key_algorithm must be Some(_)")));
    +        }
    +        Ok(Self {
    +            key_algorithm,
    +            sym_algorithm,
    +            vm,
    +        })
    +    }
    +}
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/provider.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/provider.rs.html new file mode 100644 index 00000000..bedf8598 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/knox/provider.rs.html @@ -0,0 +1,355 @@ +provider.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +
    use std::any::Any;
    +
    +use tracing::instrument;
    +
    +use crate::{
    +    common::{
    +        crypto::algorithms::{
    +            encryption::{
    +                AsymmetricEncryption,
    +                BlockCiphers,
    +                EccCurves,
    +                EccSchemeAlgorithm,
    +                SymmetricMode,
    +            },
    +            KeyBits
    +        },
    +        error::SecurityModuleError,
    +        traits::module_provider::Provider,
    +    },
    +    tpm::{
    +        android::knox::{
    +            interface::jni::RustDef,
    +            KnoxProvider
    +        },
    +        core::error::TpmError::UnsupportedOperation
    +    }
    +};
    +
    +/// Implements the `Provider` trait, providing cryptographic operations utilizing a TPM.
    +///
    +/// This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations
    +/// In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault
    +impl Provider for KnoxProvider {
    +    /// Creates a new cryptographic key identified by `key_id`.
    +    ///
    +    /// This method creates a persistent cryptographic key using the specified algorithm
    +    /// and identifier, making it retrievable for future operations. The key is created
    +    /// and stored in Knox Vault. This method also loads the key for further usage, therefore it is
    +    /// not necessary to load a key after creating it.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A string slice that uniquely identifies the key to be created.
    +    /// * `Box<dyn Any`- This box must contain a KnoxConfig, otherwise an Error is returned.
    +    ///    A KnoxConfig must contain the algorithm to be used as well as a reference to the JavaVM of the app
    +    ///    More details can be found in its [documentation](crate::tpm::android::knox::KnoxConfig)
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` that, on success, contains `Ok(())`, indicating that the key was created and stored successfully.
    +    /// On failure, it returns a `SecurityModuleError`.
    +    #[instrument(skip(config))]
    +    fn create_key(&mut self, key_id: &str, config: Box<dyn Any>) -> Result<(), SecurityModuleError> {
    +        let config = Self::downcast_config(config)?;
    +        let sym_alg = config.sym_algorithm;
    +        let asym_alg = config.key_algorithm;
    +
    +        //Stores the vm for future access
    +        self.set_config(config);
    +
    +        let key_algo;
    +        if asym_alg.is_some() && sym_alg.is_none() {
    +            key_algo = match asym_alg.expect("Already checked") {
    +                AsymmetricEncryption::Rsa(bitslength) => {
    +                    match bitslength {
    +                        KeyBits::Bits512 => { String::from("RSA;512;SHA-256;PKCS1") }
    +                        KeyBits::Bits1024 => { String::from("RSA;1024;SHA-256;PKCS1") }
    +                        KeyBits::Bits2048 => { String::from("RSA;2048;SHA-256;PKCS1") }
    +                        KeyBits::Bits3072 => { String::from("RSA;3072;SHA-256;PKCS1") }
    +                        KeyBits::Bits4096 => { String::from("RSA;4096;SHA-256;PKCS1") }
    +                        KeyBits::Bits8192 => { String::from("RSA;8192;SHA-256;PKCS1") }
    +                        _ => {
    +                            return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                                format!("Unsupported asymmetric encryption algorithm: {:?}",
    +                                        asym_alg))));
    +                        }
    +                    }
    +                }
    +                AsymmetricEncryption::Ecc(scheme) => {
    +                    match scheme {
    +                        EccSchemeAlgorithm::EcDsa(curve) => {
    +                            match curve {
    +                                EccCurves::P256 => { String::from("EC;secp256r1;SHA-256") }
    +                                EccCurves::P384 => { String::from("EC;secp384r1;SHA-256") }
    +                                EccCurves::P521 => { String::from("EC;secp521r1;SHA-256") }
    +                                //    EccCurves::Curve25519 => { String::from("EC;X25519;SHA-256") } <- x25519 may ONLY be used for key agreement, not signing
    +                                _ => {
    +                                    return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                                        format!("Unsupported asymmetric encryption algorithm: {:?}",
    +                                                asym_alg))));
    +                                }
    +                            }
    +                        }
    +                        _ => {
    +                            return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                                format!("Unsupported asymmetric encryption algorithm: {:?}",
    +                                        asym_alg))));
    +                        }
    +                    }
    +                }
    +            };
    +        } else if asym_alg.is_none() && sym_alg.is_some() {
    +            key_algo = match sym_alg.expect("Already checked") {
    +                BlockCiphers::Des => { String::from("DESede;168;CBC;PKCS7Padding") }
    +
    +                BlockCiphers::Aes(block, bitslength) => {
    +                    let mut rv = String::from("AES;");
    +                    match bitslength {
    +                        KeyBits::Bits128 => { rv += "128;"; }
    +                        KeyBits::Bits192 => { rv += "192;"; }
    +                        KeyBits::Bits256 => { rv += "256;"; }
    +                        _ => {
    +                            return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                                format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg))));
    +                        }
    +                    }
    +                    match block {
    +                        SymmetricMode::Gcm => { rv += "GCM;NoPadding" }
    +                        SymmetricMode::Cbc => { rv += "CBC;PKCS7Padding" }
    +                        SymmetricMode::Ctr => { rv += "CTR;NoPadding" }
    +                        _ => {
    +                            return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                                format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg))));
    +                        }
    +                    }
    +                    rv
    +                }
    +                _ => {
    +                    return Err(SecurityModuleError::Tpm(UnsupportedOperation(
    +                        format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg))));
    +                }
    +            };
    +        } else {
    +            return Err(SecurityModuleError::CreationError(format!(
    +                "wrong parameters in KnoxConfig:
    +                Exactly one of either sym_algorithm or key_algorithm must be Some().\
    +                sym_algorithm: {:?}\
    +                key_algorithm: {:?}",
    +                sym_alg,
    +                asym_alg)));
    +        }
    +        RustDef::create_key(&self.get_env()?, String::from(key_id), key_algo)
    +    }
    +
    +    /// Loads an existing cryptographic key identified by `key_id`.
    +    ///
    +    /// This method attempts to load a persisted cryptographic key by its identifier from the TPM.
    +    /// If successful, it enables the key to be used for cryptographic operations.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A string slice that uniquely identifies the key to be loaded.
    +    /// * `Box<dyn Any`- This box must contain a KnoxConfig, otherwise an Error is returned.
    +    ///    A KnoxConfig must contain the algorithm to be used as well as a reference to the JavaVM of the app
    +    ///    More details can be found in its [documentation](crate::tpm::android::knox::KnoxConfig)
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `Result` that, on success, contains `Ok(())`, indicating that the key was loaded successfully.
    +    /// On failure, it returns a `SecurityModuleError`.
    +    #[instrument]
    +    fn load_key(&mut self, key_id: &str, config: Box<dyn Any>) -> Result<(), SecurityModuleError> {
    +        //Stores the vm for future access
    +        let config = Self::downcast_config(config)?;
    +        self.set_config(config);
    +
    +        RustDef::load_key(&self.get_env()?, key_id.to_string())
    +    }
    +
    +    ///This function ordinarily initialises the HSM.
    +    /// For our implementation, this is not needed. You do not need to call this method,
    +    /// and it will always return Ok(()) if you do.
    +    fn initialize_module(&mut self) -> Result<(), SecurityModuleError> {
    +        Ok(())
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/mod.rs.html new file mode 100644 index 00000000..13d71c5d --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/mod.rs.html @@ -0,0 +1,1097 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +197
    +198
    +199
    +200
    +201
    +202
    +203
    +204
    +205
    +206
    +207
    +208
    +209
    +210
    +211
    +212
    +213
    +214
    +215
    +216
    +217
    +218
    +219
    +220
    +221
    +222
    +223
    +224
    +225
    +226
    +227
    +228
    +229
    +230
    +231
    +232
    +233
    +234
    +235
    +236
    +237
    +238
    +239
    +240
    +241
    +242
    +243
    +244
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    +254
    +255
    +256
    +257
    +258
    +259
    +260
    +261
    +262
    +263
    +264
    +265
    +266
    +267
    +268
    +269
    +270
    +271
    +272
    +273
    +274
    +275
    +276
    +277
    +278
    +279
    +280
    +281
    +282
    +283
    +284
    +285
    +286
    +287
    +288
    +289
    +290
    +291
    +292
    +293
    +294
    +295
    +296
    +297
    +298
    +299
    +300
    +301
    +302
    +303
    +304
    +305
    +306
    +307
    +308
    +309
    +310
    +311
    +312
    +313
    +314
    +315
    +316
    +317
    +318
    +319
    +320
    +321
    +322
    +323
    +324
    +325
    +326
    +327
    +328
    +329
    +330
    +331
    +332
    +333
    +334
    +335
    +336
    +337
    +338
    +339
    +340
    +341
    +342
    +343
    +344
    +345
    +346
    +347
    +348
    +349
    +350
    +351
    +352
    +353
    +354
    +355
    +356
    +357
    +358
    +359
    +360
    +361
    +362
    +363
    +364
    +365
    +366
    +367
    +368
    +369
    +370
    +371
    +372
    +373
    +374
    +375
    +376
    +377
    +378
    +379
    +380
    +381
    +382
    +383
    +384
    +385
    +386
    +387
    +388
    +389
    +390
    +391
    +392
    +393
    +394
    +395
    +396
    +397
    +398
    +399
    +400
    +401
    +402
    +403
    +404
    +405
    +406
    +407
    +408
    +409
    +410
    +411
    +412
    +413
    +414
    +415
    +416
    +417
    +418
    +419
    +420
    +421
    +422
    +423
    +424
    +425
    +426
    +427
    +428
    +429
    +430
    +431
    +432
    +433
    +434
    +435
    +436
    +437
    +438
    +439
    +440
    +441
    +442
    +443
    +444
    +445
    +446
    +447
    +448
    +449
    +450
    +451
    +452
    +453
    +454
    +455
    +456
    +457
    +458
    +459
    +460
    +461
    +462
    +463
    +464
    +465
    +466
    +467
    +468
    +469
    +470
    +471
    +472
    +473
    +474
    +475
    +476
    +477
    +478
    +479
    +480
    +481
    +482
    +483
    +484
    +485
    +486
    +487
    +488
    +489
    +490
    +491
    +492
    +493
    +494
    +495
    +496
    +497
    +498
    +499
    +500
    +501
    +502
    +503
    +504
    +505
    +506
    +507
    +508
    +509
    +510
    +511
    +512
    +513
    +514
    +515
    +516
    +517
    +518
    +519
    +520
    +521
    +522
    +523
    +524
    +525
    +526
    +527
    +528
    +529
    +530
    +531
    +532
    +533
    +534
    +535
    +536
    +537
    +538
    +539
    +540
    +541
    +542
    +543
    +544
    +545
    +546
    +547
    +
    pub mod android_logger;
    +pub mod config;
    +pub(crate) mod error;
    +pub mod knox;
    +pub(crate) mod utils;
    +pub(crate) mod wrapper;
    +
    +use std::any::Any;
    +
    +use robusta_jni::jni::objects::JObject;
    +use tracing::{debug, info, instrument};
    +use utils::{
    +    get_algorithm, get_cipher_mode, get_digest, get_key_size, get_padding, get_signature_algorithm,
    +    get_signature_padding, get_sym_block_mode,
    +};
    +
    +use crate::common::crypto::KeyUsage;
    +use crate::common::error::SecurityModuleError;
    +use crate::common::traits::key_handle::KeyHandle;
    +use crate::common::{
    +    crypto::algorithms::encryption::{AsymmetricEncryption, BlockCiphers},
    +    traits::module_provider::Provider,
    +};
    +use crate::tpm::android::config::AndroidConfig;
    +use crate::tpm::android::wrapper::key_store::key_store::jni::KeyStore;
    +use crate::tpm::android::wrapper::key_store::signature::jni::Signature;
    +use crate::tpm::core::error::ToTpmError;
    +use crate::tpm::core::error::TpmError;
    +
    +const ANDROID_KEYSTORE: &str = "AndroidKeyStore";
    +
    +/// A TPM-based cryptographic provider for managing cryptographic keys and performing
    +/// cryptographic operations in an Android environment.
    +///
    +/// This provider uses the Android Keystore API to interact
    +/// with the Trusted Execution Environment (TEE), or the devices Secure Element(Like the Titan M chip in a Google Pixel)
    +/// for operations like signing, encryption, and decryption.
    +/// It provides a secure and hardware-backed solution for managing cryptographic keys and performing
    +/// cryptographic operations on Android.
    +#[derive(Debug)]
    +pub(crate) struct AndroidProvider {
    +    key_id: String,
    +    config: Option<AndroidConfig>,
    +}
    +
    +impl AndroidProvider {
    +    /// Constructs a new `AndroidProvider`.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - A string identifier for the cryptographic key to be managed by this provider.
    +    /// * `config` - Configuration
    +    ///
    +    /// # Returns
    +    ///
    +    /// A new instance of `AndroidProvider` with the specified `key_id`.
    +    #[instrument]
    +    pub fn new(key_id: String) -> Self {
    +        Self {
    +            key_id,
    +            config: None,
    +        }
    +    }
    +
    +    fn apply_config(&mut self, config: AndroidConfig) -> Result<(), SecurityModuleError> {
    +        // TODO: verify config
    +        self.config = Some(config);
    +        Ok(())
    +    }
    +}
    +
    +/// Implementation of the `Provider` trait for the Android platform.
    +///
    +/// This struct provides methods for key generation, key loading, and module initialization
    +/// specific to Android.
    +impl Provider for AndroidProvider {
    +    /// Generates a key with the parameters specified when the module was initialized.
    +    ///
    +    /// The key is generated using the Android Keystore API and is stored securely in the device's
    +    /// Trusted Execution Environment (TEE) or Secure Element. It first attempts to generate a key
    +    /// withing the devices StrongBox (Secure Element), and if that fails, because it is not available,
    +    /// it falls back to the TEE. We have to do this because the KeyStore does not automatically select
    +    /// the highest security level available.
    +    ///
    +    /// # Java Example
    +    ///
    +    /// ```java
    +    /// KeyPairGenerator kpg = KeyPairGenerator.getInstance(
    +    ///         KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
    +    /// kpg.initialize(new KeyGenParameterSpec.Builder(
    +    ///         alias,
    +    ///         KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
    +    ///         .setDigests(KeyProperties.DIGEST_SHA256,
    +    ///             KeyProperties.DIGEST_SHA512)
    +    ///         .build());
    +    /// KeyPair kp = kpg.generateKeyPair();
    +    /// ```
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - The identifier for the key.
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns `Ok(())` if the key generation is successful, otherwise returns an error of type `SecurityModuleError`.
    +    #[instrument]
    +    fn create_key(
    +        &mut self,
    +        key_id: &str,
    +        config: Box<dyn Any>,
    +    ) -> Result<(), SecurityModuleError> {
    +        info!("generating key! {}", key_id);
    +
    +        // load config
    +        let config = *config
    +            .downcast::<AndroidConfig>()
    +            .map_err(|_| SecurityModuleError::InitializationError("Wrong Config".to_owned()))?;
    +
    +        let env = config
    +            .vm
    +            .as_ref()
    +            .expect("cannot happen, already checked")
    +            .get_env()
    +            .map_err(|_| {
    +                TpmError::InitializationError(
    +                    "Could not get java environment, this should never happen".to_owned(),
    +                )
    +            })?;
    +
    +        // build up key specs
    +        let mut kps_builder =
    +            wrapper::key_generation::builder::Builder::new(&env, key_id.to_owned(), 1 | 2 | 4 | 8)
    +                .err_internal()?;
    +
    +        match config.mode {
    +            config::EncryptionMode::Sym(cipher) => {
    +                match cipher {
    +                    BlockCiphers::Aes(mode, size) => {
    +                        kps_builder = kps_builder
    +                            .set_block_modes(&env, vec![get_sym_block_mode(mode)?])
    +                            .err_internal()?
    +                            .set_encryption_paddings(&env, vec![get_padding(config.mode)?])
    +                            .err_internal()?
    +                            .set_key_size(&env, Into::<u32>::into(size) as i32)
    +                            .err_internal()?;
    +                    }
    +                    BlockCiphers::Des => {
    +                        kps_builder = kps_builder
    +                            .set_block_modes(&env, vec!["CBC".to_owned()])
    +                            .err_internal()?
    +                            .set_encryption_paddings(&env, vec![get_padding(config.mode)?])
    +                            .err_internal()?;
    +                    }
    +                    BlockCiphers::TripleDes(_)
    +                    | BlockCiphers::Rc2(_)
    +                    | BlockCiphers::Camellia(_, _) => {
    +                        Err(TpmError::UnsupportedOperation("not supported".to_owned()))?
    +                    }
    +                };
    +                kps_builder = kps_builder
    +                    .set_is_strongbox_backed(&env, config.hardware_backed)
    +                    .err_internal()?;
    +
    +                let kps = kps_builder.build(&env).err_internal()?;
    +
    +                let kg = wrapper::key_generation::key_generator::jni::KeyGenerator::getInstance(
    +                    &env,
    +                    get_algorithm(config.mode)?,
    +                    ANDROID_KEYSTORE.to_owned(),
    +                )
    +                .err_internal()?;
    +                kg.init(&env, kps.raw.as_obj()).err_internal()?;
    +
    +                kg.generateKey(&env).err_internal()?;
    +            }
    +            config::EncryptionMode::ASym { algo, digest } => {
    +                match algo {
    +                    AsymmetricEncryption::Rsa(_key_bits) => {
    +                        kps_builder = kps_builder
    +                            .set_digests(&env, vec![get_digest(digest)?])
    +                            .err_internal()?
    +                            .set_signature_paddings(&env, vec![get_signature_padding()?])
    +                            .err_internal()?
    +                            .set_encryption_paddings(&env, vec![get_padding(config.mode)?])
    +                            .err_internal()?
    +                            .set_key_size(&env, get_key_size(algo)? as i32)
    +                            .err_internal()?;
    +                    }
    +                    AsymmetricEncryption::Ecc(_scheme) => {
    +                        kps_builder = kps_builder
    +                            .set_digests(&env, vec![get_digest(digest)?])
    +                            .err_internal()?;
    +                    }
    +                };
    +                kps_builder = kps_builder
    +                    .set_is_strongbox_backed(&env, config.hardware_backed)
    +                    .err_internal()?;
    +
    +                let kps = kps_builder.build(&env).err_internal()?;
    +
    +                let kpg = wrapper::key_generation::key_pair_generator::jni::KeyPairGenerator::getInstance(
    +                    &env,
    +                    get_algorithm(config.mode)?,
    +                    ANDROID_KEYSTORE.to_owned(),
    +                    )
    +                    .err_internal()?;
    +
    +                kpg.initialize(&env, kps.raw.as_obj()).err_internal()?;
    +
    +                kpg.generateKeyPair(&env).err_internal()?;
    +            }
    +        }
    +
    +        debug!("key generated");
    +        self.apply_config(config)?;
    +
    +        Ok(())
    +    }
    +
    +    /// Loads a key with the specified `key_id`.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_id` - The identifier for the key.
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns `Ok(())` if the key loading is successful, otherwise returns an error of type `SecurityModuleError`.
    +    #[instrument]
    +    fn load_key(&mut self, key_id: &str, config: Box<dyn Any>) -> Result<(), SecurityModuleError> {
    +        key_id.clone_into(&mut self.key_id);
    +
    +        // load config
    +        let config = *config
    +            .downcast::<AndroidConfig>()
    +            .map_err(|_| SecurityModuleError::InitializationError("Wrong Config".to_owned()))?;
    +        self.apply_config(config)?;
    +
    +        Ok(())
    +    }
    +
    +    /// Initializes the module with the specified parameters.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `key_algorithm` - The asymmetric encryption algorithm to be used.
    +    /// * `sym_algorithm` - The block cipher algorithm to be used (optional).
    +    /// * `hash` - The hash algorithm to be used (optional).
    +    /// * `key_usages` - The list of key usages.
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns `Ok(())` if the module initialization is successful, otherwise returns an error of type `SecurityModuleError`.
    +    #[instrument]
    +    fn initialize_module(&mut self) -> Result<(), SecurityModuleError> {
    +        Ok(())
    +    }
    +}
    +
    +/// Implementation of the `KeyHandle` trait for the `AndroidProvider` struct.
    +/// All of the functions in this KeyHandle are basically re-implementations
    +/// of the equivalent Java functions in the Android KeyStore API.
    +impl KeyHandle for AndroidProvider {
    +    /// Signs the given data using the Android KeyStore.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `data` - Byte array of data to be signed.
    +    ///
    +    /// # Java Example
    +    ///
    +    /// ```java
    +    /// KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
    +    /// ks.load(null);
    +    /// KeyStore.Entry entry = ks.getEntry(alias, null);
    +    /// if (!(entry instanceof PrivateKeyEntry)) {
    +    ///     Log.w(TAG, "Not an instance of a PrivateKeyEntry");
    +    ///     return null;
    +    /// }
    +    /// Signature s = Signature.getInstance("SHA256withECDSA");
    +    /// s.initSign(((PrivateKeyEntry) entry).getPrivateKey());
    +    /// s.update(data);
    +    /// byte[] signature = s.sign();
    +    /// ```
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns a `Result` containing the signed data as a `Vec<u8>` if successful, or a `SecurityModuleError` if an error occurs.
    +    #[instrument]
    +    fn sign_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        // check that signing is allowed
    +        let config = self
    +            .config
    +            .as_ref()
    +            .ok_or(SecurityModuleError::InitializationError(
    +                "Module is not initialized".to_owned(),
    +            ))?;
    +
    +        if !config.key_usages.contains(&KeyUsage::SignEncrypt) {
    +            return Err(TpmError::UnsupportedOperation(
    +                "KeyUsage::SignEncrypt was not provided".to_owned(),
    +            )
    +            .into());
    +        }
    +
    +        let env = config
    +            .vm
    +            .as_ref()
    +            .ok_or_else(|| TpmError::InitializationError("Module is not initialized".to_owned()))?
    +            .get_env()
    +            .map_err(|_| {
    +                TpmError::InitializationError(
    +                    "Could not get java environment, this should never happen".to_owned(),
    +                )
    +            })?;
    +
    +        let key_store = KeyStore::getInstance(&env, ANDROID_KEYSTORE.to_string()).err_internal()?;
    +        key_store.load(&env, None).err_internal()?;
    +
    +        let private_key = key_store
    +            .getKey(&env, self.key_id.clone(), JObject::null())
    +            .err_internal()?;
    +
    +        let signature_algorithm = get_signature_algorithm(config.mode)?;
    +        debug!("Signature Algorithm: {}", signature_algorithm);
    +
    +        let s = Signature::getInstance(&env, signature_algorithm.to_string()).err_internal()?;
    +
    +        s.initSign(&env, private_key.raw.as_obj()).err_internal()?;
    +
    +        let data_bytes = data.to_vec().into_boxed_slice();
    +
    +        s.update(&env, data_bytes).err_internal()?;
    +        debug!("Signature Init: {}", s.toString(&env).unwrap());
    +
    +        let output = s.sign(&env).err_internal()?;
    +
    +        Ok(output)
    +    }
    +
    +    /// Decrypts the given encrypted data using the Android KeyStore.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `encrypted_data` - The encrypted data to be decrypted.
    +    ///
    +    /// # Java Example
    +    ///
    +    /// ```java
    +    /// KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
    +    /// keyStore.load(null);
    +    /// PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEYNAME, null);
    +    /// PublicKey publicKey = keyStore.getCertificate(KEYNAME).getPublicKey();
    +    /// Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    +    /// cipher.init(Cipher.DECRYPT_MODE, privateKey);
    +    /// byte[] decrypted = cipher.doFinal(encrypted);
    +    /// ```
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns a `Result` containing the decrypted data as a `Vec<u8>` if successful, or a `SecurityModuleError` if an error occurs.
    +    #[instrument]
    +    fn decrypt_data(&self, encrypted_data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        info!("decrypting data");
    +
    +        let config = self
    +            .config
    +            .as_ref()
    +            .ok_or(SecurityModuleError::InitializationError(
    +                "Module is not initialized".to_owned(),
    +            ))?;
    +
    +        let env = config
    +            .vm
    +            .as_ref()
    +            .ok_or_else(|| TpmError::InitializationError("Module is not initialized".to_owned()))?
    +            .get_env()
    +            .map_err(|_| {
    +                TpmError::InitializationError(
    +                    "Could not get java environment, this should never happen".to_owned(),
    +                )
    +            })?;
    +
    +        let cipher_mode = get_cipher_mode(config.mode)?;
    +
    +        let key_store = KeyStore::getInstance(&env, ANDROID_KEYSTORE.to_owned()).err_internal()?;
    +        key_store.load(&env, None).err_internal()?;
    +
    +        let key = key_store
    +            .getKey(&env, self.key_id.to_owned(), JObject::null())
    +            .err_internal()?;
    +
    +        let cipher = wrapper::key_store::cipher::jni::Cipher::getInstance(&env, cipher_mode)
    +            .err_internal()?;
    +        cipher.init(&env, 2, key.raw.as_obj()).err_internal()?;
    +
    +        let decrypted = cipher
    +            .doFinal(&env, encrypted_data.to_vec())
    +            .err_internal()?;
    +
    +        debug!("decrypted data: {:?}", decrypted);
    +        Ok(decrypted)
    +    }
    +
    +    /// Encrypts the given data using the Android KeyStore.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `data` - The data to be encrypted.
    +    ///
    +    /// # Java Example
    +    ///
    +    /// ```java
    +    /// KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
    +    /// keyStore.load(null);
    +    /// PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEYNAME, null);
    +    /// PublicKey publicKey = keyStore.getCertificate(KEYNAME).getPublicKey();
    +    /// Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    +    /// byte[] encrypted;
    +    /// cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    +    /// encrypted = cipher.doFinal(text.getBytes());
    +    /// ```
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns a `Result` containing the encrypted data as a `Vec<u8>` if successful, or a `SecurityModuleError` if an error occurs.
    +    #[instrument]
    +    fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>, SecurityModuleError> {
    +        info!("encrypting");
    +
    +        let config = self
    +            .config
    +            .as_ref()
    +            .ok_or(SecurityModuleError::InitializationError(
    +                "Module is not initialized".to_owned(),
    +            ))?;
    +
    +        let env = config
    +            .vm
    +            .as_ref()
    +            .ok_or_else(|| TpmError::InitializationError("Module is not initialized".to_owned()))?
    +            .get_env()
    +            .map_err(|_| {
    +                TpmError::InitializationError(
    +                    "Could not get java environment, this should never happen".to_owned(),
    +                )
    +            })?;
    +
    +        let key_store = KeyStore::getInstance(&env, ANDROID_KEYSTORE.to_owned()).err_internal()?;
    +        key_store.load(&env, None).err_internal()?;
    +
    +        let key = key_store
    +            .getCertificate(&env, self.key_id.to_owned())
    +            .err_internal()?
    +            .getPublicKey(&env)
    +            .err_internal()?;
    +
    +        let public_alg = key.getAlgorithm(&env).unwrap();
    +        debug!("Public Alg: {}", public_alg);
    +
    +        let cipher = wrapper::key_store::cipher::jni::Cipher::getInstance(
    +            &env,
    +            get_cipher_mode(config.mode)?,
    +        )
    +        .err_internal()?;
    +
    +        cipher.init(&env, 1, key.raw.as_obj()).err_internal()?;
    +
    +        let encrypted = cipher.doFinal(&env, data.to_vec()).err_internal()?;
    +
    +        debug!("encrypted: {:?}", encrypted);
    +        Ok(encrypted)
    +    }
    +
    +    /// Verifies the signature of the given data using the Android KeyStore.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `data` - The data whose signature needs to be verified.
    +    /// * `signature` - The signature to be verified.
    +    ///
    +    /// # Java Example
    +    ///
    +    /// ```java
    +    /// KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
    +    /// ks.load(null);
    +    /// KeyStore.Entry entry = ks.getEntry(alias, null);
    +    /// if (!(entry instanceof PrivateKeyEntry)) {
    +    ///     Log.w(TAG, "Not an instance of a PrivateKeyEntry");
    +    ///     return false;
    +    /// }
    +    /// Signature s = Signature.getInstance("SHA256withECDSA");
    +    /// s.initVerify(((PrivateKeyEntry) entry).getCertificate());
    +    /// s.update(data);
    +    /// boolean valid = s.verify(signature);
    +    /// ```
    +    ///
    +    /// # Returns
    +    ///
    +    /// Returns a `Result` containing `true` if the signature is valid, `false` otherwise, or a `SecurityModuleError` if an error occurs.
    +    #[instrument]
    +    fn verify_signature(&self, data: &[u8], signature: &[u8]) -> Result<bool, SecurityModuleError> {
    +        info!("verifiying");
    +
    +        let config = self
    +            .config
    +            .as_ref()
    +            .ok_or(SecurityModuleError::InitializationError(
    +                "Module is not initialized".to_owned(),
    +            ))?;
    +
    +        let env = config
    +            .vm
    +            .as_ref()
    +            .ok_or_else(|| TpmError::InitializationError("Module is not initialized".to_owned()))?
    +            .get_env()
    +            .map_err(|_| {
    +                TpmError::InitializationError(
    +                    "Could not get java environment, this should never happen".to_owned(),
    +                )
    +            })?;
    +
    +        let key_store = KeyStore::getInstance(&env, ANDROID_KEYSTORE.to_string()).err_internal()?;
    +        key_store.load(&env, None).err_internal()?;
    +
    +        let signature_algorithm = get_signature_algorithm(config.mode)?;
    +        debug!("Signature Algorithm: {}", signature_algorithm);
    +
    +        let s = Signature::getInstance(&env, signature_algorithm.to_string()).err_internal()?;
    +
    +        let cert = key_store
    +            .getCertificate(&env, self.key_id.clone())
    +            .err_internal()?;
    +
    +        s.initVerify(&env, cert).err_internal()?;
    +        debug!("Signature Init: {}", s.toString(&env).unwrap());
    +
    +        let data_bytes = data.to_vec().into_boxed_slice();
    +        s.update(&env, data_bytes).err_internal()?;
    +
    +        let signature_boxed = signature.to_vec().into_boxed_slice();
    +        let output = s.verify(&env, signature_boxed).err_internal()?;
    +        debug!("Signature verified: {:?}", output);
    +
    +        Ok(output)
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/utils.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/utils.rs.html new file mode 100644 index 00000000..d3b0c4e6 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/utils.rs.html @@ -0,0 +1,395 @@ +utils.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +
    use crate::{
    +    common::{
    +        crypto::algorithms::{
    +            encryption::{AsymmetricEncryption, BlockCiphers, SymmetricMode},
    +            hashes::{Hash, Sha2Bits},
    +        },
    +        error::SecurityModuleError,
    +    },
    +    tpm::core::error::TpmError,
    +};
    +
    +use super::config::EncryptionMode;
    +
    +pub fn get_algorithm(enc: EncryptionMode) -> Result<String, SecurityModuleError> {
    +    Ok(match enc {
    +        EncryptionMode::Sym(algo) => match algo {
    +            BlockCiphers::Aes(_, _) => "AES",
    +            BlockCiphers::TripleDes(_) => "DESede",
    +            BlockCiphers::Des | BlockCiphers::Rc2(_) | BlockCiphers::Camellia(_, _) => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()))?
    +            }
    +        },
    +        EncryptionMode::ASym { algo, digest: _ } => match algo {
    +            AsymmetricEncryption::Rsa(_) => "RSA",
    +            AsymmetricEncryption::Ecc(_) => "EC",
    +        },
    +    }
    +    .to_owned())
    +}
    +
    +pub fn get_cipher_mode(e_mode: EncryptionMode) -> Result<String, SecurityModuleError> {
    +    match e_mode {
    +        EncryptionMode::Sym(cipher) => match cipher {
    +            BlockCiphers::Aes(mode, _) => Ok(format!(
    +                "AES/{}/{}",
    +                get_sym_block_mode(mode)?,
    +                get_padding(e_mode)?
    +            )),
    +            BlockCiphers::TripleDes(_) => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +            BlockCiphers::Des => Ok("DES".to_owned()),
    +            BlockCiphers::Rc2(_) => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +            BlockCiphers::Camellia(_, _) => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +        },
    +        EncryptionMode::ASym { algo, digest: _ } => match algo {
    +            AsymmetricEncryption::Rsa(_) => Ok(format!("RSA/ECB/{}", get_padding(e_mode)?)),
    +            AsymmetricEncryption::Ecc(_) => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +        },
    +    }
    +}
    +
    +pub fn get_sym_block_mode(mode: SymmetricMode) -> Result<String, SecurityModuleError> {
    +    Ok(match mode {
    +        SymmetricMode::Gcm => "GCM",
    +        SymmetricMode::Ecb => "ECB",
    +        SymmetricMode::Cbc => "CBC",
    +        SymmetricMode::Ctr => "CTR",
    +        SymmetricMode::Cfb | SymmetricMode::Ofb | SymmetricMode::Ccm => {
    +            Err(TpmError::UnsupportedOperation(
    +                "Only GCM, ECB, CBC and CTR as blockmodes supported".to_owned(),
    +            ))?
    +        }
    +    }
    +    .to_owned())
    +}
    +
    +pub fn get_padding(mode: EncryptionMode) -> Result<String, SecurityModuleError> {
    +    Ok(match mode {
    +        EncryptionMode::Sym(BlockCiphers::Aes(_, _)) => "PKCS5Padding",
    +        EncryptionMode::ASym { algo: _, digest: _ } => "PKCS1Padding",
    +        _ => "PKCS1Padding",
    +    }
    +    .to_owned())
    +}
    +
    +pub fn get_signature_padding() -> Result<String, SecurityModuleError> {
    +    Ok("PKCS1".to_owned())
    +}
    +
    +pub fn get_digest(digest: Hash) -> Result<String, SecurityModuleError> {
    +    match digest {
    +        Hash::Sha1 => Ok("SHA-1".to_owned()),
    +        Hash::Sha2(size) => match size {
    +            Sha2Bits::Sha224 => Ok("SHA-224".to_owned()),
    +            Sha2Bits::Sha256 => Ok("SHA-256".to_owned()),
    +            Sha2Bits::Sha384 => Ok("SHA-384".to_owned()),
    +            Sha2Bits::Sha512 => Ok("SHA-512".to_owned()),
    +            Sha2Bits::Sha512_224 | Sha2Bits::Sha512_256 => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +        },
    +        Hash::Md5 => Ok("MD5".to_owned()),
    +        Hash::Sha3(_) | Hash::Md2 | Hash::Md4 | Hash::Ripemd160 => {
    +            Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +        }
    +    }
    +}
    +
    +pub fn get_hash_name(hash: Hash) -> Result<String, SecurityModuleError> {
    +    match hash {
    +        Hash::Sha1 => Ok("SHA1".to_owned()),
    +        Hash::Sha2(size) => match size {
    +            Sha2Bits::Sha224 => Ok("SHA224".to_owned()),
    +            Sha2Bits::Sha256 => Ok("SHA256".to_owned()),
    +            Sha2Bits::Sha384 => Ok("SHA384".to_owned()),
    +            Sha2Bits::Sha512 => Ok("SHA512".to_owned()),
    +            Sha2Bits::Sha512_224 | Sha2Bits::Sha512_256 => {
    +                Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +            }
    +        },
    +        Hash::Md5 => Ok("MD5".to_owned()),
    +        Hash::Sha3(_) | Hash::Md2 | Hash::Md4 | Hash::Ripemd160 => {
    +            Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +        }
    +    }
    +}
    +
    +pub fn get_key_size(algo: AsymmetricEncryption) -> Result<u32, SecurityModuleError> {
    +    match algo {
    +        AsymmetricEncryption::Rsa(size) => Ok(Into::<u32>::into(size)),
    +        AsymmetricEncryption::Ecc(_) => {
    +            Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +        }
    +    }
    +}
    +
    +pub fn get_curve(algo: AsymmetricEncryption) -> Result<String, SecurityModuleError> {
    +    match algo {
    +        AsymmetricEncryption::Rsa(_) => {
    +            Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +        }
    +        AsymmetricEncryption::Ecc(scheme) => {
    +            let curve = match scheme {
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::EcDsa(v) => v,
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::EcDh(v) => v,
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::EcDaa(v) => v,
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::Sm2(v) => v,
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::EcSchnorr(v) => {
    +                    v
    +                }
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::EcMqv(v) => v,
    +                crate::common::crypto::algorithms::encryption::EccSchemeAlgorithm::Null => {
    +                    return Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +                }
    +            };
    +            Ok(match curve {
    +                crate::common::crypto::algorithms::encryption::EccCurves::P256 => "secp256r1",
    +                crate::common::crypto::algorithms::encryption::EccCurves::P384 => "secp384r1",
    +                crate::common::crypto::algorithms::encryption::EccCurves::P521 => "secp521r1",
    +                crate::common::crypto::algorithms::encryption::EccCurves::Secp256k1 => "secp256k1",
    +                crate::common::crypto::algorithms::encryption::EccCurves::BrainpoolP256r1 => {
    +                    "brainpoolP256r1"
    +                }
    +                crate::common::crypto::algorithms::encryption::EccCurves::BrainpoolP384r1 => {
    +                    "brainpoolP384r1"
    +                }
    +                crate::common::crypto::algorithms::encryption::EccCurves::BrainpoolP512r1 => {
    +                    "brainpoolP512r1"
    +                }
    +                crate::common::crypto::algorithms::encryption::EccCurves::BrainpoolP638 => {
    +                    return Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +                }
    +                crate::common::crypto::algorithms::encryption::EccCurves::Curve25519 => "X25519",
    +                crate::common::crypto::algorithms::encryption::EccCurves::Curve448 => "X448",
    +                crate::common::crypto::algorithms::encryption::EccCurves::Frp256v1 => {
    +                    return Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +                }
    +            }
    +            .to_owned())
    +        }
    +    }
    +}
    +
    +pub fn get_signature_algorithm(mode: EncryptionMode) -> Result<String, SecurityModuleError> {
    +    match mode {
    +        EncryptionMode::Sym(_) => {
    +            Err(TpmError::UnsupportedOperation("not supported".to_owned()).into())
    +        }
    +        EncryptionMode::ASym { algo, digest } => {
    +            let part1 = match algo {
    +                AsymmetricEncryption::Rsa(_) => "RSA",
    +                AsymmetricEncryption::Ecc(_) => "ECDSA",
    +            };
    +            let part2 = get_hash_name(digest)?;
    +
    +            Ok(format!("{part2}with{part1}"))
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/builder.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/builder.rs.html new file mode 100644 index 00000000..1ab6a464 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/builder.rs.html @@ -0,0 +1,553 @@ +builder.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +140
    +141
    +142
    +143
    +144
    +145
    +146
    +147
    +148
    +149
    +150
    +151
    +152
    +153
    +154
    +155
    +156
    +157
    +158
    +159
    +160
    +161
    +162
    +163
    +164
    +165
    +166
    +167
    +168
    +169
    +170
    +171
    +172
    +173
    +174
    +175
    +176
    +177
    +178
    +179
    +180
    +181
    +182
    +183
    +184
    +185
    +186
    +187
    +188
    +189
    +190
    +191
    +192
    +193
    +194
    +195
    +196
    +197
    +198
    +199
    +200
    +201
    +202
    +203
    +204
    +205
    +206
    +207
    +208
    +209
    +210
    +211
    +212
    +213
    +214
    +215
    +216
    +217
    +218
    +219
    +220
    +221
    +222
    +223
    +224
    +225
    +226
    +227
    +228
    +229
    +230
    +231
    +232
    +233
    +234
    +235
    +236
    +237
    +238
    +239
    +240
    +241
    +242
    +243
    +244
    +245
    +246
    +247
    +248
    +249
    +250
    +251
    +252
    +253
    +254
    +255
    +256
    +257
    +258
    +259
    +260
    +261
    +262
    +263
    +264
    +265
    +266
    +267
    +268
    +269
    +270
    +271
    +272
    +273
    +274
    +275
    +
    use crate::tpm::android::wrapper::key_generation::key_gen_parameter_spec::jni::KeyGenParameterSpec;
    +
    +use robusta_jni::jni::errors::Result as JniResult;
    +use robusta_jni::jni::objects::{AutoLocal, JObject, JValue};
    +use robusta_jni::jni::sys::jsize;
    +use robusta_jni::jni::JNIEnv;
    +
    +/// Builder for creating `KeyGenParameterSpec` objects.
    +/// This class is an inner class of `KeyGenParameterSpec`. For that reason, it could not
    +/// be implemented using the help of `robusta_jni`. `robusta_jni` does not support inner classes.
    +pub struct Builder<'env: 'borrow, 'borrow> {
    +    raw: AutoLocal<'env, 'borrow>,
    +}
    +
    +impl<'env: 'borrow, 'borrow> Builder<'env, 'borrow> {
    +    /// Creates a new `Builder` instance.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `env` - The JNI environment.
    +    /// * `keystore_alias` - The alias for the keystore.
    +    /// * `purposes` - The purposes for which the key can be used.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the new `Builder` instance.
    +    pub fn new(
    +        env: &'borrow JNIEnv<'env>,
    +        keystore_alias: String,
    +        purposes: i32,
    +    ) -> JniResult<Self> {
    +        let class = env.find_class("android/security/keystore/KeyGenParameterSpec$Builder")?;
    +        let jstring_keystore_alias = env.new_string(keystore_alias)?;
    +        let args = [Into::into(jstring_keystore_alias), JValue::from(purposes)];
    +        let obj = env.new_object(class, "(Ljava/lang/String;I)V", &args)?;
    +        Ok(Self {
    +            raw: AutoLocal::new(env, Into::<JObject>::into(obj)),
    +        })
    +    }
    +
    +    /// Sets the digests for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `digests` - The digests to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_digests(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        digests: Vec<String>,
    +    ) -> JniResult<Self> {
    +        let string_class = env.find_class("java/lang/String")?;
    +        let digest_array =
    +            env.new_object_array(digests.len() as jsize, string_class, JObject::null())?;
    +        for (i, digest) in digests.iter().enumerate() {
    +            let jstring_digest = env.new_string(digest)?;
    +            env.set_object_array_element(digest_array, i as jsize, jstring_digest)?;
    +        }
    +
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setDigests",
    +            "([Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[digest_array.into()],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets the encryption paddings for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `paddings` - The encryption paddings to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_encryption_paddings(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        paddings: Vec<String>,
    +    ) -> JniResult<Self> {
    +        let string_class = env.find_class("java/lang/String")?;
    +        let padding_array =
    +            env.new_object_array(paddings.len() as jsize, string_class, JObject::null())?;
    +        for (i, padding) in paddings.iter().enumerate() {
    +            let jstring_padding = env.new_string(padding)?;
    +            env.set_object_array_element(padding_array, i as jsize, jstring_padding)?;
    +        }
    +
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setEncryptionPaddings",
    +            "([Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[padding_array.into()],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets the signature paddings for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `paddings` - The signature paddings to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_signature_paddings(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        paddings: Vec<String>,
    +    ) -> JniResult<Self> {
    +        let string_class = env.find_class("java/lang/String")?;
    +        let padding_array =
    +            env.new_object_array(paddings.len() as jsize, string_class, JObject::null())?;
    +        for (i, padding) in paddings.iter().enumerate() {
    +            let jstring_padding = env.new_string(padding)?;
    +            env.set_object_array_element(padding_array, i as jsize, jstring_padding)?;
    +        }
    +
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setSignaturePaddings",
    +            "([Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[padding_array.into()],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets the block modes for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `block_modes` - The block modes to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_block_modes(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        block_modes: Vec<String>,
    +    ) -> JniResult<Self> {
    +        let string_class = env.find_class("java/lang/String")?;
    +        let block_mode_array =
    +            env.new_object_array(block_modes.len() as jsize, string_class, JObject::null())?;
    +        for (i, block_mode) in block_modes.iter().enumerate() {
    +            let jstring_block_mode = env.new_string(block_mode)?;
    +            env.set_object_array_element(block_mode_array, i as jsize, jstring_block_mode)?;
    +        }
    +
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setBlockModes",
    +            "([Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[block_mode_array.into()],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets the key size for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `key_size` - The key size to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_key_size(mut self, env: &'borrow JNIEnv<'env>, key_size: i32) -> JniResult<Self> {
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setKeySize",
    +            "(I)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[JValue::Int(key_size)],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets the algorithm parameter specification for the key.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `spec` - The algorithm parameter specification to set.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_algorithm_parameter_spec(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        spec: JObject,
    +    ) -> JniResult<Self> {
    +        let result = env.call_method(
    +        self.raw.as_obj(),
    +        "setAlgorithmParameterSpec",
    +        "(Ljavax/crypto/spec/AlgorithmParameterSpec;)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +        &[JValue::Object(spec)],
    +    )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Sets whether the key is backed by a strongbox.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    /// * `is_strongbox_backed` - Whether the key is strongbox backed.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the updated `Builder` instance.
    +    pub fn set_is_strongbox_backed(
    +        mut self,
    +        env: &'borrow JNIEnv<'env>,
    +        is_strongbox_backed: bool,
    +    ) -> JniResult<Self> {
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "setIsStrongBoxBacked",
    +            "(Z)Landroid/security/keystore/KeyGenParameterSpec$Builder;",
    +            &[JValue::Bool(is_strongbox_backed.into())],
    +        )?;
    +        self.raw = AutoLocal::new(env, result.l()?);
    +        Ok(self)
    +    }
    +
    +    /// Builds the `KeyGenParameterSpec` object.
    +    ///
    +    /// # Arguments
    +    ///
    +    /// * `self` - The `Builder` instance.
    +    /// * `env` - The JNI environment.
    +    ///
    +    /// # Returns
    +    ///
    +    /// A `JniResult` containing the built `KeyGenParameterSpec` object.
    +    pub fn build(
    +        self,
    +        env: &'borrow JNIEnv<'env>,
    +    ) -> JniResult<KeyGenParameterSpec<'env, 'borrow>> {
    +        let result = env.call_method(
    +            self.raw.as_obj(),
    +            "build",
    +            "()Landroid/security/keystore/KeyGenParameterSpec;",
    +            &[],
    +        )?;
    +        Ok(KeyGenParameterSpec {
    +            raw: AutoLocal::new(env, result.l()?),
    +        })
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key.rs.html new file mode 100644 index 00000000..83892086 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key.rs.html @@ -0,0 +1,117 @@ +key.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for key generation in Android.
    +pub mod jni {
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{errors::Result as JniResult, objects::AutoLocal, JNIEnv},
    +    };
    +
    +    /// Represents a key in Java's `java.security` package.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct Key<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(javax.crypto)]
    +    pub struct SecretKey<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    /// Represents a public key in Java's `java.security` package.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct PublicKey<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> PublicKey<'env, 'borrow> {
    +        /// Converts the public key to its string representation.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +
    +        /// Retrieves the algorithm used by the public key.
    +        pub extern "java" fn getAlgorithm(&self, _env: &JNIEnv) -> JniResult<String> {}
    +    }
    +
    +    /// Represents a private key in Java's `java.security` package.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct PrivateKey<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> PrivateKey<'env, 'borrow> {
    +        /// Converts the private key to its string representation.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +
    +        /// Retrieves the algorithm used by the private key.
    +        pub extern "java" fn getAlgorithm(&self, _env: &JNIEnv) -> JniResult<String> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_gen_parameter_spec.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_gen_parameter_spec.rs.html new file mode 100644 index 00000000..07dbe9dd --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_gen_parameter_spec.rs.html @@ -0,0 +1,91 @@ +key_gen_parameter_spec.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the KeyGenParameterSpec struct/class.
    +pub mod jni {
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{errors::Result as JniResult, objects::AutoLocal, JNIEnv},
    +    };
    +
    +    /// Represents the KeyGenParameterSpec struct in the android.security.keystore package.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(android.security.keystore)]
    +    pub struct KeyGenParameterSpec<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> KeyGenParameterSpec<'env, 'borrow> {
    +        /// Retrieves the supported digest algorithms for the key generation.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A Result containing a vector of strings representing the supported digest algorithms,
    +        /// or an error if the JNI call fails.
    +        pub extern "java" fn getDigests(&self, env: &JNIEnv) -> JniResult<Vec<String>> {}
    +
    +        /// Checks if the key generation is backed by a StrongBox.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// A Result containing a boolean value indicating whether the key generation is backed by a StrongBox,
    +        /// or an error if the JNI call fails.
    +        pub extern "java" fn isStrongBoxBacked(&self, env: &JNIEnv) -> JniResult<bool> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_generator.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_generator.rs.html new file mode 100644 index 00000000..926772c8 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_generator.rs.html @@ -0,0 +1,81 @@ +key_generator.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +pub mod jni {
    +    use crate::tpm::android::wrapper::key_generation::key::jni::SecretKey;
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Result as JniResult,
    +            objects::{AutoLocal, JObject},
    +            JNIEnv,
    +        },
    +    };
    +
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(javax.crypto)]
    +    pub struct KeyGenerator<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> KeyGenerator<'env, 'borrow> {
    +        pub extern "java" fn getInstance(
    +            env: &'borrow JNIEnv<'env>,
    +            algorithm: String,
    +            provider: String,
    +        ) -> JniResult<Self> {
    +        }
    +
    +        pub extern "java" fn init(
    +            &self,
    +            env: &JNIEnv,
    +            #[input_type("Ljava/security/spec/AlgorithmParameterSpec;")] params: JObject,
    +        ) -> JniResult<()> {
    +        }
    +
    +        pub extern "java" fn generateKey(&self, _env: &'borrow JNIEnv) -> JniResult<SecretKey> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair.rs.html new file mode 100644 index 00000000..85005c30 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair.rs.html @@ -0,0 +1,63 @@ +key_pair.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the `KeyPair` struct used in Android TPM key generation.
    +pub mod jni {
    +    use crate::tpm::android::wrapper::key_generation::key::jni::{PrivateKey, PublicKey};
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{errors::Result as JniResult, objects::AutoLocal, JNIEnv},
    +    };
    +
    +    /// Represents a Java `KeyPair` object.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct KeyPair<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> KeyPair<'env, 'borrow> {
    +        /// Returns a string representation of the `KeyPair` object.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +
    +        /// Returns the public key associated with the `KeyPair` object.
    +        pub extern "java" fn getPublic(&self, _env: &'borrow JNIEnv) -> JniResult<PublicKey> {}
    +
    +        /// Returns the private key associated with the `KeyPair` object.
    +        pub extern "java" fn getPrivate(&self, _env: &'borrow JNIEnv) -> JniResult<PrivateKey> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair_generator.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair_generator.rs.html new file mode 100644 index 00000000..a7e616de --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/key_pair_generator.rs.html @@ -0,0 +1,211 @@ +key_pair_generator.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the `KeyPairGenerator` class in the Android TPM wrapper.
    +pub mod jni {
    +    use crate::tpm::android::wrapper::key_generation::key_pair::jni::KeyPair;
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Result as JniResult,
    +            objects::{AutoLocal, JObject},
    +            JNIEnv,
    +        },
    +    };
    +
    +    /// Represents a Java `KeyPairGenerator` object.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct KeyPairGenerator<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> KeyPairGenerator<'env, 'borrow> {
    +        /// Returns an instance of `KeyPairGenerator` for the specified algorithm and provider.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `algorithm` - The name of the algorithm.
    +        /// * `provider` - The name of the provider.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the `KeyPairGenerator` instance.
    +        pub extern "java" fn getInstance(
    +            env: &'borrow JNIEnv<'env>,
    +            algorithm: String,
    +            provider: String,
    +        ) -> JniResult<Self> {
    +        }
    +
    +        /// Returns a string representation of the `KeyPairGenerator` object.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `_env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the string representation.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +
    +        /// Returns the algorithm name associated with the `KeyPairGenerator` object.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `_env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the algorithm name.
    +        pub extern "java" fn getAlgorithm(&self, _env: &JNIEnv) -> JniResult<String> {}
    +
    +        /// Initializes the `KeyPairGenerator` object with the specified algorithm parameters.
    +        ///
    +        /// Initializes the key pair generator using the specified parameter set and the SecureRandom
    +        /// implementation of the highest-priority installed provider as the source of randomness.
    +        /// (If none of the installed providers supply an implementation of SecureRandom, a system-provided source of randomness is used.)
    +        ///
    +        /// Could not be implemented using `robusta_jni` because the params parameter is the class
    +        /// AlgorithmParameterSpec. AlgorithmParameterSpec is an interface and we need to pass an object
    +        /// of type KeyGenParameterSpec. This causes the signatures to not match, meaning the jni call fails.
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `params` - The algorithm parameter specification.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` indicating success or failure.
    +        pub extern "java" fn initialize(
    +            &self,
    +            env: &JNIEnv,
    +            #[input_type("Ljava/security/spec/AlgorithmParameterSpec;")] params: JObject,
    +        ) -> JniResult<()> {
    +        }
    +
    +        /// Generates a key pair using the `KeyPairGenerator` object.
    +        ///
    +        /// If this KeyPairGenerator has not been initialized explicitly, provider-specific defaults
    +        /// will be used for the size and other (algorithm-specific) values of the generated keys.
    +        /// This will generate a new key pair every time it is called.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `_env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the generated `KeyPair`.
    +        pub extern "java" fn generateKeyPair(&self, _env: &'borrow JNIEnv) -> JniResult<KeyPair> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/mod.rs.html new file mode 100644 index 00000000..911d5577 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/mod.rs.html @@ -0,0 +1,21 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +
    #![allow(clippy::needless_borrow)]
    +
    +pub mod builder;
    +pub mod key;
    +pub mod key_gen_parameter_spec;
    +pub mod key_generator;
    +pub mod key_pair;
    +pub mod key_pair_generator;
    +pub mod secure_random;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/secure_random.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/secure_random.rs.html new file mode 100644 index 00000000..54b6ffd0 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_generation/secure_random.rs.html @@ -0,0 +1,63 @@ +secure_random.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the `SecureRandom` class in the `java.security` package.
    +/// This might not even be necessary. The `SecureRandom` is automatically generated by `KeyPairGenerator.initialize`
    +pub mod jni {
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::errors::Result as JniResult,
    +        jni::objects::AutoLocal,
    +        jni::JNIEnv,
    +    };
    +
    +    /// Represents the `SecureRandom` class in Java.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct SecureRandom<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> SecureRandom<'env, 'borrow> {
    +        /// Constructs a new `SecureRandom` instance.
    +        #[constructor]
    +        pub extern "java" fn new(env: &'borrow JNIEnv<'env>) -> JniResult<Self> {}
    +
    +        /// Returns the algorithm name of the `SecureRandom` instance.
    +        pub extern "java" fn getAlgorithm(&self, env: &JNIEnv<'env>) -> JniResult<String> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/cipher.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/cipher.rs.html new file mode 100644 index 00000000..dc779171 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/cipher.rs.html @@ -0,0 +1,175 @@ +cipher.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the Cipher class in the javax.crypto package.
    +pub mod jni {
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Result as JniResult,
    +            objects::{AutoLocal, JObject, JValue},
    +            sys::jbyteArray,
    +            JNIEnv,
    +        },
    +    };
    +
    +    /// Represents a Cipher object in Java.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(javax.crypto)]
    +    pub struct Cipher<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> Cipher<'env, 'borrow> {
    +        /// Creates a new instance of the Cipher class.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNIEnv object.
    +        /// * `transformation` - the name of the transformation, e.g., DES/CBC/PKCS5Padding. See the Cipher section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard transformation names.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Cipher object that implements the specified transformation.
    +        pub extern "java" fn getInstance(
    +            env: &'borrow JNIEnv<'env>,
    +            transformation: String,
    +        ) -> JniResult<Self> {
    +        }
    +
    +        /// Initializes the Cipher object with the specified operation mode and key.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNIEnv object.
    +        /// * `opmode` - The operation mode.
    +        /// * `key` - The key object.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a JniResult indicating success or failure.
    +        pub extern "java" fn init(
    +            &self,
    +            env: &'borrow JNIEnv<'env>,
    +            opmode: i32,
    +            #[input_type("Ljava/security/Key;")] key: JObject,
    +        ) -> JniResult<()> {
    +        }
    +
    +        /// Performs the final operation of the Cipher, processing any remaining data.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNIEnv object.
    +        /// * `input` - The input data.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a JniResult containing the output data.
    +        pub fn doFinal(&self, env: &JNIEnv, input: Vec<u8>) -> JniResult<Vec<u8>> {
    +            let input_array = env.byte_array_from_slice(&input)?;
    +
    +            let output = env.call_method(
    +                self.raw.as_obj(),
    +                "doFinal",
    +                "([B)[B",
    +                &[JValue::from(input_array)],
    +            )?;
    +
    +            let output_array = output.l()?.into_inner() as jbyteArray;
    +            let output_vec = env.convert_byte_array(output_array).unwrap();
    +
    +            Ok(output_vec)
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/key_store.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/key_store.rs.html new file mode 100644 index 00000000..2b2942b0 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/key_store.rs.html @@ -0,0 +1,265 @@ +key_store.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the KeyStore functionality in Android.
    +pub mod jni {
    +    use crate::tpm::android::wrapper::key_generation::key::jni::{Key, PublicKey};
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Result as JniResult,
    +            objects::{AutoLocal, JObject},
    +            JNIEnv,
    +        },
    +    };
    +
    +    /// Represents a KeyStore object in Java.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct KeyStore<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> KeyStore<'env, 'borrow> {
    +        /// Retrieves an instance of the KeyStore class.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `type1` - The type of the KeyStore. In java the paramenter is just 'type', but we have to use 'type1' because 'type' is a reserved keyword in Rust.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a keystore object of the specified type.
    +        pub extern "java" fn getInstance(
    +            env: &'borrow JNIEnv<'env>,
    +            type1: String,
    +        ) -> JniResult<Self> {
    +        }
    +
    +        /// Retrieves a certificate from the KeyStore.
    +        ///
    +        /// Returns the certificate associated with the given alias.
    +        /// If the given alias name identifies an entry created by a call to setCertificateEntry,
    +        /// or created by a call to setEntry with a TrustedCertificateEntry, then the trusted certificate
    +        /// contained in that entry is returned.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `alias` - The alias name.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the Certificate instance.
    +        pub extern "java" fn getCertificate(
    +            &self,
    +            env: &'borrow JNIEnv<'env>,
    +            alias: String,
    +        ) -> JniResult<Certificate> {
    +        }
    +
    +        /// Retrieves a key from the KeyStore.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `alias` - The alias of the key.
    +        /// * `password` - The password for the key.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the Key instance.
    +        pub extern "java" fn getKey(
    +            &self,
    +            env: &'borrow JNIEnv<'env>,
    +            alias: String,
    +            #[input_type("[C")] password: JObject,
    +        ) -> JniResult<Key> {
    +        }
    +
    +        /// Loads the KeyStore.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `param` - An optional parameter for loading the KeyStore.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` indicating the success or failure of the operation.
    +        pub fn load(&self, env: &JNIEnv, param: Option<JObject>) -> JniResult<()> {
    +            let param_obj = param.unwrap_or(JObject::null());
    +            env.call_method(
    +                self.raw.as_obj(),
    +                "load",
    +                "(Ljava/security/KeyStore$LoadStoreParameter;)V",
    +                &[Into::into(param_obj)],
    +            )?;
    +            Ok(())
    +        }
    +    }
    +
    +    /// Represents a Certificate object in Java.
    +    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security.cert)]
    +    pub struct Certificate<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> Certificate<'env, 'borrow> {
    +        /// Retrieves the public key from the Certificate.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a `JniResult` containing the PublicKey instance.
    +        pub extern "java" fn getPublicKey(
    +            &self,
    +            env: &'borrow JNIEnv<'env>,
    +        ) -> JniResult<PublicKey<'env, 'borrow>> {
    +        }
    +
    +        /// toString Java method of the Certificate class.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/mod.rs.html new file mode 100644 index 00000000..c4a0eb6d --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/mod.rs.html @@ -0,0 +1,13 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +
    #![allow(clippy::needless_borrow)]
    +
    +pub mod cipher;
    +pub mod key_store;
    +pub mod signature;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/signature.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/signature.rs.html new file mode 100644 index 00000000..701c3483 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/key_store/signature.rs.html @@ -0,0 +1,269 @@ +signature.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +
    use robusta_jni::bridge;
    +
    +#[bridge]
    +/// This module contains the JNI bindings for the Signature class in the Java security package.
    +pub mod jni {
    +    use crate::tpm::android::wrapper::key_store::key_store::jni::Certificate;
    +    use robusta_jni::{
    +        convert::{IntoJavaValue, Signature as JavaSignature, TryFromJavaValue, TryIntoJavaValue},
    +        jni::{
    +            errors::Result as JniResult,
    +            objects::{AutoLocal, JObject, JValue},
    +            JNIEnv,
    +        },
    +    };
    +
    +    /// Represents a Signature object in Java.
    +    #[derive(JavaSignature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    +    #[package(java.security)]
    +    pub struct Signature<'env: 'borrow, 'borrow> {
    +        #[instance]
    +        pub raw: AutoLocal<'env, 'borrow>,
    +    }
    +
    +    impl<'env: 'borrow, 'borrow> Signature<'env, 'borrow> {
    +        /// Creates a new instance of the Signature class with the specified algorithm.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `algorithm` - The algorithm to use for the Signature instance.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result containing the Signature instance if successful, or an error if it fails.
    +        pub extern "java" fn getInstance(
    +            env: &'borrow JNIEnv<'env>,
    +            algorithm: String,
    +        ) -> JniResult<Self> {
    +        }
    +
    +        /// Signs the data using the Signature instance.
    +        ///
    +        /// Could not be implemented using `robusta_jni` because the Java method returns a byte array,
    +        /// and byte arrays are not supported as a return value by `robusta_jni`.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result containing the signed data as a Vec<u8> if successful, or an error if it fails.
    +        pub fn sign(&self, env: &JNIEnv) -> JniResult<Vec<u8>> {
    +            let result = env.call_method(self.raw.as_obj(), "sign", "()[B", &[])?;
    +
    +            let byte_array = result.l()?.into_inner();
    +            let output = env.convert_byte_array(byte_array)?;
    +
    +            Ok(output)
    +        }
    +
    +        /// Initializes the Signature instance for signing with the specified private key.
    +        ///         
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `privateKey` - The private key to use for signing.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result indicating success or failure.
    +        pub extern "java" fn initSign(
    +            &self,
    +            env: &JNIEnv,
    +            #[input_type("Ljava/security/PrivateKey;")] privateKey: JObject,
    +        ) -> JniResult<()> {
    +        }
    +
    +        /// Initializes the Signature instance for verification with the specified certificate.
    +        ///
    +        /// Could not be implemented using `robusta_jni` because for some reason it doesn't
    +        /// recognize the `Certificate` signature correctly.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `env` - The JNI environment.
    +        /// * `certificate` - The certificate to use for verification.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result indicating success or failure.
    +        pub fn initVerify(&self, env: &JNIEnv, certificate: Certificate) -> JniResult<()> {
    +            let certificate_obj = certificate.raw.as_obj();
    +
    +            env.call_method(
    +                self.raw.as_obj(),
    +                "initVerify",
    +                "(Ljava/security/cert/Certificate;)V",
    +                &[JValue::from(certificate_obj)],
    +            )?;
    +
    +            Ok(())
    +        }
    +
    +        /// Verifies the signature against the specified data.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `_env` - The JNI environment.
    +        /// * `signature` - The signature to verify.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result indicating whether the signature is valid or not.
    +        pub extern "java" fn verify(&self, _env: &JNIEnv, signature: Box<[u8]>) -> JniResult<bool> {
    +        }
    +
    +        /// Updates the Signature instance with additional data to be signed or verified.
    +        ///
    +        /// # Arguments
    +        ///
    +        /// * `_env` - The JNI environment.
    +        /// * `data` - The data to update the Signature instance with.
    +        ///
    +        /// # Returns
    +        ///
    +        /// Returns a Result indicating success or failure.
    +        pub extern "java" fn update(&self, _env: &JNIEnv, data: Box<[u8]>) -> JniResult<()> {}
    +
    +        /// toString Java method of the Signature class.
    +        pub extern "java" fn toString(&self, _env: &JNIEnv) -> JniResult<String> {}
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/mod.rs.html new file mode 100644 index 00000000..6e5524fa --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/android/wrapper/mod.rs.html @@ -0,0 +1,125 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +
    use robusta_jni::jni::{
    +    self,
    +    sys::{jint, jsize},
    +    JavaVM,
    +};
    +
    +use crate::tpm::core::error::TpmError;
    +
    +pub(crate) mod key_generation;
    +pub(crate) mod key_store;
    +
    +/// This function gets the current Java VM running for the Android app.
    +/// Every Android app can have only 1 JVM running, so we can't just create a new one.
    +/// Normally it would be possible to just call the "JNI_GetCreatedJavaVMs" C function, but we can't link against it for some reason
    +/// so we have to load the symbol manually using the libloading crate.
    +pub(super) fn get_java_vm() -> Result<JavaVM, TpmError> {
    +    // using jni_sys::JNI_GetCreatedJavaVMs crashes, bc the symbol is not loaded into the process for some reason
    +    // instead we use libloading to load the symbol ourselves
    +    pub type JniGetCreatedJavaVms = unsafe extern "system" fn(
    +        vmBuf: *mut *mut jni::sys::JavaVM,
    +        bufLen: jsize,
    +        nVMs: *mut jsize,
    +    ) -> jint;
    +    pub const JNI_GET_JAVA_VMS_NAME: &[u8] = b"JNI_GetCreatedJavaVMs";
    +
    +    let lib = libloading::os::unix::Library::this();
    +    // let lib = unsafe { libloading::os::unix::Library::new("libart.so") }
    +    // .map_err(|e| TpmError::InitializationError(format!("could not find libart.so: {e}")))?;
    +
    +    let get_created_java_vms: JniGetCreatedJavaVms = unsafe {
    +        *lib.get(JNI_GET_JAVA_VMS_NAME).map_err(|e| {
    +            TpmError::InitializationError(format!("function JNI_GET_JAVA_VMS_NAME not loaded: {e}"))
    +        })?
    +    };
    +
    +    // now that we have the function, we can call it
    +    let mut buffer = [std::ptr::null_mut::<jni::sys::JavaVM>(); 1];
    +    let buffer_ptr = buffer.as_mut_ptr();
    +    let mut found_vms = 0;
    +    let found_vm_ptr = &mut found_vms as *mut i32;
    +    let res = unsafe { get_created_java_vms(buffer_ptr, 1, found_vm_ptr) };
    +
    +    if res != jni::sys::JNI_OK {
    +        return Err(TpmError::InitializationError(
    +            "Unable to get existing JVMs".to_owned(),
    +        ));
    +    }
    +
    +    if found_vms == 0 {
    +        return Err(TpmError::InitializationError(
    +            "No running JVMs found".to_owned(),
    +        ));
    +    }
    +
    +    let jvm = unsafe {
    +        JavaVM::from_raw(buffer[0]).map_err(|e| TpmError::InitializationError(e.to_string()))?
    +    };
    +    jvm.attach_current_thread()
    +        .map_err(|e| TpmError::InitializationError(e.to_string()))?;
    +    Ok(jvm)
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/core/error.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/core/error.rs.html new file mode 100644 index 00000000..d8099e79 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/core/error.rs.html @@ -0,0 +1,145 @@ +error.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +
    use std::fmt;
    +
    +/// Represents errors that can occur when interacting with a Trusted Platform Module (TPM).
    +///
    +/// This enum encapsulates different types of errors that may arise during TPM operations,
    +/// including I/O errors, Windows API errors, initialization errors, and unsupported operations.
    +/// It is designed to provide a clear and descriptive representation of the error, facilitating
    +/// error handling and logging.
    +#[derive(Debug)]
    +#[repr(C)]
    +pub enum TpmError {
    +    /// Error related to I/O operations, wrapping a `std::io::Error`.
    +    Io(std::io::Error),
    +    /// Error originating from Windows API calls, wrapping a `windows::core::Error`.
    +    /// This variant is only available on Windows platforms.
    +    #[cfg(feature = "win")]
    +    Win(windows::core::Error),
    +    /// Error occurring during TPM initialization, containing an error message.
    +    InitializationError(String),
    +    /// Error indicating that an attempted operation is unsupported, containing a description.
    +    UnsupportedOperation(String),
    +    /// Error indicating that an internal error occured, possibly caused by ffi bindings
    +    InternalError(Box<dyn std::error::Error>),
    +}
    +
    +impl fmt::Display for TpmError {
    +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    +        write!(f, "{}", self.description())
    +    }
    +}
    +
    +impl TpmError {
    +    /// Provides a human-readable description of the TPM error.
    +    ///
    +    /// This implementation ensures that errors can be easily logged or displayed to the user,
    +    /// with a clear indication of the error's nature and origin.
    +    pub fn description(&self) -> String {
    +        match self {
    +            TpmError::Io(err) => format!("IO error: {}", err),
    +            #[cfg(feature = "win")]
    +            TpmError::Win(err) => format!("Windows error: {}", err),
    +            TpmError::InitializationError(msg) => format!("Initialization error: {}", msg),
    +            TpmError::UnsupportedOperation(msg) => format!("Unsupported operation: {}", msg),
    +            TpmError::InternalError(e) => format!("Internal error: {}", e),
    +        }
    +    }
    +}
    +
    +/// A trait to allow ergonomic conversions to TpmError
    +pub trait ToTpmError<T> {
    +    /// Wrap any error in TpmError::InternalError
    +    /// the wrapped error can be accessed througth the error trait
    +    fn err_internal(self) -> Result<T, TpmError>;
    +}
    +
    +/// Enables `TpmError` to be treated as a trait object for any error (`dyn std::error::Error`).
    +///
    +/// This implementation allows for compatibility with Rust's standard error handling mechanisms,
    +/// facilitating the propagation and inspection of errors through the `source` method.
    +impl std::error::Error for TpmError {
    +    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    +        match self {
    +            TpmError::Io(ref err) => Some(err),
    +            #[cfg(feature = "win")]
    +            TpmError::Win(ref err) => Some(err),
    +            // `InitializationError` and `UnsupportedOperation` do not wrap another error,
    +            // so they return `None` for their source.
    +            _ => None,
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/core/instance.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/core/instance.rs.html new file mode 100644 index 00000000..d843affb --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/core/instance.rs.html @@ -0,0 +1,281 @@ +instance.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +71
    +72
    +73
    +74
    +75
    +76
    +77
    +78
    +79
    +80
    +81
    +82
    +83
    +84
    +85
    +86
    +87
    +88
    +89
    +90
    +91
    +92
    +93
    +94
    +95
    +96
    +97
    +98
    +99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    +118
    +119
    +120
    +121
    +122
    +123
    +124
    +125
    +126
    +127
    +128
    +129
    +130
    +131
    +132
    +133
    +134
    +135
    +136
    +137
    +138
    +139
    +
    use crate::common::traits::module_provider::Provider;
    +#[cfg(feature = "linux")]
    +use crate::tpm::linux::TpmProvider;
    +#[cfg(feature = "win")]
    +use crate::tpm::win::TpmProvider as WinTpmProvider;
    +use std::sync::{Arc, Mutex};
    +
    +/// Represents the different environments where a Trusted Platform Module (TPM) can operate.
    +///
    +/// This enum is designed to distinguish between various operating system environments,
    +/// including Windows, macOS, Linux, and Android-specific TPM types. It provides a unified
    +/// way to handle TPM operations across different platforms.
    +#[repr(C)]
    +#[derive(Eq, Hash, PartialEq, Clone, Debug)]
    +pub enum TpmType {
    +    /// Represents the TPM environment on Windows platforms.
    +    #[cfg(feature = "win")]
    +    Windows,
    +    /// Represents the TPM environment on macOS platforms.
    +    #[cfg(feature = "macos")]
    +    MacOs,
    +    /// Represents the TPM environment on Linux platforms.
    +    #[cfg(feature = "linux")]
    +    Linux,
    +    /// Represents the TPM environment on Android platforms, with a specific `AndroidTpmType`.
    +    #[cfg(feature = "android")]
    +    Android(AndroidTpmType),
    +    /// Represents an unsupported or unknown TPM environment.
    +    None,
    +}
    +
    +/// Enumerates the types of TPM available on Android platforms.
    +///
    +/// Currently, this enum includes a single variant, `Knox`, which represents
    +/// Samsung's Knox security platform that incorporates TPM functionalities.
    +#[repr(C)]
    +#[derive(Eq, Hash, PartialEq, Clone, Debug)]
    +#[cfg(feature = "android")]
    +pub enum AndroidTpmType {
    +    /// Android Provider using the Android Keystore API
    +    Keystore,
    +    /// Represents the Samsung Knox security platform with TPM functionalities.
    +    Knox,
    +}
    +
    +/// Provides a default `TpmType` based on the compile-time target operating system.
    +///
    +/// This implementation enables automatic selection of the TPM type most appropriate
    +/// for the current target OS, facilitating platform-agnostic TPM handling.
    +impl Default for TpmType {
    +    #[allow(unreachable_code)]
    +    fn default() -> Self {
    +        #[cfg(feature = "win")]
    +        return TpmType::Windows;
    +
    +        #[cfg(feature = "macos")]
    +        return TpmType::MacOs;
    +
    +        #[cfg(feature = "linux")]
    +        return TpmType::Linux;
    +
    +        #[cfg(feature = "android")]
    +        return TpmType::Android(AndroidTpmType::Knox);
    +
    +        TpmType::None
    +    }
    +}
    +
    +/// Enables conversion from a string slice to a `TpmType`.
    +///
    +/// This implementation allows for dynamic TPM type determination based on string values,
    +/// useful for configuration or runtime environment specification.
    +impl From<&str> for TpmType {
    +    fn from(s: &str) -> Self {
    +        match s {
    +            #[cfg(feature = "win")]
    +            "Windows" => TpmType::Windows,
    +            #[cfg(feature = "macos")]
    +            "MacOs" => TpmType::MacOs,
    +            #[cfg(feature = "linux")]
    +            "Linux" => TpmType::Linux,
    +            #[cfg(feature = "android")]
    +            "Android" => TpmType::Android(AndroidTpmType::Knox),
    +            _ => panic!("Unsupported TpmType"),
    +        }
    +    }
    +}
    +
    +/// Manages instances of TPM providers based on the specified `TpmType`.
    +///
    +/// This structure is responsible for creating and encapsulating a TPM provider instance,
    +/// allowing for TPM operations such as key management and cryptographic functions
    +/// to be performed in a platform-specific manner.
    +#[repr(C)]
    +pub struct TpmInstance {
    +    name: String,
    +    instance: Box<dyn Provider>,
    +}
    +
    +/// Facilitates the creation and management of TPM provider instances.
    +impl TpmInstance {
    +    /// Creates a new TPM provider instance based on the specified `TpmType`.
    +    ///
    +    /// This method abstracts over the differences between TPM implementations across
    +    /// various platforms, providing a unified interface for TPM operations.
    +    ///
    +    /// # Arguments
    +    /// * `key_id` - A unique identifier for the TPM key.
    +    /// * `tpm_type` - A reference to the `TpmType` indicating the environment of the TPM.
    +    ///
    +    /// # Returns
    +    /// An `Arc<dyn Provider>` encapsulating the created TPM provider instance.
    +    pub fn create_instance(key_id: String, tpm_type: &TpmType) -> Arc<Mutex<dyn Provider>> {
    +        match tpm_type {
    +            #[cfg(feature = "win")]
    +            TpmType::Windows => {
    +                let instance = WinTpmProvider::new(key_id);
    +                Arc::new(Mutex::new(instance))
    +            }
    +            #[cfg(feature = "macos")]
    +            TpmType::MacOs => todo!(),
    +            #[cfg(feature = "linux")]
    +            TpmType::Linux => {
    +                let instance = TpmProvider::new(key_id);
    +                Arc::new(Mutex::new(instance))
    +            }
    +            #[cfg(feature = "android")]
    +            TpmType::Android(tpm_type) => match tpm_type {
    +                AndroidTpmType::Keystore => Arc::new(Mutex::new(
    +                    crate::tpm::android::AndroidProvider::new(key_id),
    +                )),
    +               AndroidTpmType::Knox => Arc::new(Mutex::new(
    +                    crate::tpm::android::knox::KnoxProvider::new(),
    +                )),
    +            },
    +            TpmType::None => todo!(),
    +        }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/core/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/core/mod.rs.html new file mode 100644 index 00000000..e3b9ffde --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/core/mod.rs.html @@ -0,0 +1,7 @@ +mod.rs - source +
    1
    +2
    +
    pub mod error;
    +pub mod instance;
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/src/crypto_layer/tpm/mod.rs.html b/Documentation/RustDoc/src/crypto_layer/tpm/mod.rs.html new file mode 100644 index 00000000..b6a97ed0 --- /dev/null +++ b/Documentation/RustDoc/src/crypto_layer/tpm/mod.rs.html @@ -0,0 +1,107 @@ +mod.rs - source +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +
    use crate::common::{
    +    crypto::{
    +        algorithms::{
    +            encryption::{AsymmetricEncryption, BlockCiphers},
    +            hashes::Hash,
    +        },
    +        KeyUsage,
    +    },
    +    traits::module_provider_config::ProviderConfig,
    +};
    +use std::any::Any;
    +
    +#[cfg(feature = "android")]
    +pub mod android;
    +pub mod core;
    +#[cfg(feature = "linux")]
    +pub mod linux;
    +#[cfg(feature = "macos")]
    +pub mod macos;
    +#[cfg(feature = "win")]
    +pub mod win;
    +
    +#[derive(Debug, Clone, Default)]
    +pub struct TpmConfig {
    +    pub key_algorithm: AsymmetricEncryption,
    +    pub sym_algorithm: BlockCiphers,
    +    pub hash: Hash,
    +    pub key_usages: Vec<KeyUsage>,
    +}
    +
    +impl ProviderConfig for TpmConfig {
    +    fn as_any(&self) -> &dyn Any {
    +        self
    +    }
    +}
    +
    +impl TpmConfig {
    +    #[allow(clippy::new_ret_no_self)]
    +    pub fn new(
    +        key_algorithm: AsymmetricEncryption,
    +        sym_algorithm: BlockCiphers,
    +        hash: Hash,
    +        key_usages: Vec<KeyUsage>,
    +    ) -> Box<dyn ProviderConfig> {
    +        Box::new(Self {
    +            key_algorithm,
    +            sym_algorithm,
    +            hash,
    +            key_usages,
    +        })
    +    }
    +}
    +
    \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/COPYRIGHT-23e9bde6c69aea69.txt b/Documentation/RustDoc/static.files/COPYRIGHT-23e9bde6c69aea69.txt new file mode 100644 index 00000000..1447df79 --- /dev/null +++ b/Documentation/RustDoc/static.files/COPYRIGHT-23e9bde6c69aea69.txt @@ -0,0 +1,50 @@ +# REUSE-IgnoreStart + +These documentation pages include resources by third parties. This copyright +file applies only to those resources. The following third party resources are +included, and carry their own copyright notices and license terms: + +* Fira Sans (FiraSans-Regular.woff2, FiraSans-Medium.woff2): + + Copyright (c) 2014, Mozilla Foundation https://mozilla.org/ + with Reserved Font Name Fira Sans. + + Copyright (c) 2014, Telefonica S.A. + + Licensed under the SIL Open Font License, Version 1.1. + See FiraSans-LICENSE.txt. + +* rustdoc.css, main.js, and playpen.js: + + Copyright 2015 The Rust Developers. + Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE.txt) or + the MIT license (LICENSE-MIT.txt) at your option. + +* normalize.css: + + Copyright (c) Nicolas Gallagher and Jonathan Neal. + Licensed under the MIT license (see LICENSE-MIT.txt). + +* Source Code Pro (SourceCodePro-Regular.ttf.woff2, + SourceCodePro-Semibold.ttf.woff2, SourceCodePro-It.ttf.woff2): + + Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), + with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark + of Adobe Systems Incorporated in the United States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceCodePro-LICENSE.txt. + +* Source Serif 4 (SourceSerif4-Regular.ttf.woff2, SourceSerif4-Bold.ttf.woff2, + SourceSerif4-It.ttf.woff2): + + Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name + 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United + States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceSerif4-LICENSE.md. + +This copyright file is intended to be distributed with rustdoc output. + +# REUSE-IgnoreEnd diff --git a/Documentation/RustDoc/static.files/FiraSans-LICENSE-db4b642586e02d97.txt b/Documentation/RustDoc/static.files/FiraSans-LICENSE-db4b642586e02d97.txt new file mode 100644 index 00000000..d7e9c149 --- /dev/null +++ b/Documentation/RustDoc/static.files/FiraSans-LICENSE-db4b642586e02d97.txt @@ -0,0 +1,98 @@ +// REUSE-IgnoreStart + +Digitized data copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. +with Reserved Font Name < Fira >, + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/Documentation/RustDoc/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 b/Documentation/RustDoc/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 new file mode 100644 index 00000000..7a1e5fc5 Binary files /dev/null and b/Documentation/RustDoc/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 differ diff --git a/Documentation/RustDoc/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 b/Documentation/RustDoc/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 new file mode 100644 index 00000000..e766e06c Binary files /dev/null and b/Documentation/RustDoc/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 differ diff --git a/Documentation/RustDoc/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt b/Documentation/RustDoc/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/Documentation/RustDoc/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/Documentation/RustDoc/static.files/LICENSE-MIT-65090b722b3f6c56.txt b/Documentation/RustDoc/static.files/LICENSE-MIT-65090b722b3f6c56.txt new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/Documentation/RustDoc/static.files/LICENSE-MIT-65090b722b3f6c56.txt @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/Documentation/RustDoc/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 b/Documentation/RustDoc/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 new file mode 100644 index 00000000..1866ad4b Binary files /dev/null and b/Documentation/RustDoc/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt b/Documentation/RustDoc/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt new file mode 100644 index 00000000..4b3edc29 --- /dev/null +++ b/Documentation/RustDoc/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt @@ -0,0 +1,103 @@ +// REUSE-IgnoreStart + +Copyright (c) 2010, NAVER Corporation (https://www.navercorp.com/), + +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver NanumGothic, +NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumBrush, NanumPen, +Naver NanumPen, Naver NanumGothicEco, NanumGothicEco, Naver NanumMyeongjoEco, +NanumMyeongjoEco, Naver NanumGothicLight, NanumGothicLight, NanumBarunGothic, +Naver NanumBarunGothic, NanumSquareRound, NanumBarunPen, MaruBuri + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/Documentation/RustDoc/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 b/Documentation/RustDoc/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 new file mode 100644 index 00000000..462c34ef Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt b/Documentation/RustDoc/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt new file mode 100644 index 00000000..0d2941e1 --- /dev/null +++ b/Documentation/RustDoc/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt @@ -0,0 +1,97 @@ +// REUSE-IgnoreStart + +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/Documentation/RustDoc/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 b/Documentation/RustDoc/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 new file mode 100644 index 00000000..10b558e0 Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 b/Documentation/RustDoc/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 new file mode 100644 index 00000000..5ec64eef Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 b/Documentation/RustDoc/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 new file mode 100644 index 00000000..181a07f6 Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 b/Documentation/RustDoc/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 new file mode 100644 index 00000000..2ae08a7b Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md b/Documentation/RustDoc/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md new file mode 100644 index 00000000..175fa4f4 --- /dev/null +++ b/Documentation/RustDoc/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md @@ -0,0 +1,98 @@ + + +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. +Copyright 2014 - 2023 Adobe (http://www.adobe.com/), with Reserved Font Name ‘Source’. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + diff --git a/Documentation/RustDoc/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 b/Documentation/RustDoc/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 new file mode 100644 index 00000000..0263fc30 Binary files /dev/null and b/Documentation/RustDoc/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 differ diff --git a/Documentation/RustDoc/static.files/clipboard-7571035ce49a181d.svg b/Documentation/RustDoc/static.files/clipboard-7571035ce49a181d.svg new file mode 100644 index 00000000..8adbd996 --- /dev/null +++ b/Documentation/RustDoc/static.files/clipboard-7571035ce49a181d.svg @@ -0,0 +1 @@ + diff --git a/Documentation/RustDoc/static.files/favicon-16x16-8b506e7a72182f1c.png b/Documentation/RustDoc/static.files/favicon-16x16-8b506e7a72182f1c.png new file mode 100644 index 00000000..ea4b45ca Binary files /dev/null and b/Documentation/RustDoc/static.files/favicon-16x16-8b506e7a72182f1c.png differ diff --git a/Documentation/RustDoc/static.files/favicon-2c020d218678b618.svg b/Documentation/RustDoc/static.files/favicon-2c020d218678b618.svg new file mode 100644 index 00000000..8b34b511 --- /dev/null +++ b/Documentation/RustDoc/static.files/favicon-2c020d218678b618.svg @@ -0,0 +1,24 @@ + + + + + diff --git a/Documentation/RustDoc/static.files/favicon-32x32-422f7d1d52889060.png b/Documentation/RustDoc/static.files/favicon-32x32-422f7d1d52889060.png new file mode 100644 index 00000000..69b8613c Binary files /dev/null and b/Documentation/RustDoc/static.files/favicon-32x32-422f7d1d52889060.png differ diff --git a/Documentation/RustDoc/static.files/main-12cf3b4f4f9dc36d.js b/Documentation/RustDoc/static.files/main-12cf3b4f4f9dc36d.js new file mode 100644 index 00000000..1d8d1ccb --- /dev/null +++ b/Documentation/RustDoc/static.files/main-12cf3b4f4f9dc36d.js @@ -0,0 +1,11 @@ +"use strict";window.RUSTDOC_TOOLTIP_HOVER_MS=300;window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS=450;function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden")}function showMain(){removeClass(document.getElementById(MAIN_ID),"hidden")}function blurHandler(event,parentElem,hideCallback){if(!parentElem.contains(document.activeElement)&&!parentElem.contains(event.relatedTarget)){hideCallback()}}window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate");function setMobileTopbar(){const mobileTopbar=document.querySelector(".mobile-topbar");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileTopbar){const mobileTitle=document.createElement("h2");mobileTitle.className="location";if(hasClass(document.querySelector(".rustdoc"),"crate")){mobileTitle.innerHTML=`Crate ${window.currentCrate}`}else if(locationTitle){mobileTitle.innerHTML=locationTitle.innerHTML}mobileTopbar.appendChild(mobileTitle)}}function getVirtualKey(ev){if("key"in ev&&typeof ev.key!=="undefined"){return ev.key}const c=ev.charCode||ev.keyCode;if(c===27){return"Escape"}return String.fromCharCode(c)}const MAIN_ID="main-content";const SETTINGS_BUTTON_ID="settings-menu";const ALTERNATIVE_DISPLAY_ID="alternative-display";const NOT_DISPLAYED_ID="not-displayed";const HELP_BUTTON_ID="help-button";function getSettingsButton(){return document.getElementById(SETTINGS_BUTTON_ID)}function getHelpButton(){return document.getElementById(HELP_BUTTON_ID)}function getNakedUrl(){return window.location.href.split("?")[0].split("#")[0]}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}function getOrCreateSection(id,classes){let el=document.getElementById(id);if(!el){el=document.createElement("section");el.id=id;el.className=classes;insertAfter(el,document.getElementById(MAIN_ID))}return el}function getAlternativeDisplayElem(){return getOrCreateSection(ALTERNATIVE_DISPLAY_ID,"content hidden")}function getNotDisplayedElem(){return getOrCreateSection(NOT_DISPLAYED_ID,"hidden")}function switchDisplayedElement(elemToDisplay){const el=getAlternativeDisplayElem();if(el.children.length>0){getNotDisplayedElem().appendChild(el.firstElementChild)}if(elemToDisplay===null){addClass(el,"hidden");showMain();return}el.appendChild(elemToDisplay);hideMain();removeClass(el,"hidden")}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function preLoadCss(cssUrl){const link=document.createElement("link");link.href=cssUrl;link.rel="preload";link.as="style";document.getElementsByTagName("head")[0].appendChild(link)}(function(){const isHelpPage=window.location.pathname.endsWith("/help.html");function loadScript(url,errorCallback){const script=document.createElement("script");script.src=url;if(errorCallback!==undefined){script.onerror=errorCallback}document.head.append(script)}getSettingsButton().onclick=event=>{if(event.ctrlKey||event.altKey||event.metaKey){return}window.hideAllModals(false);addClass(getSettingsButton(),"rotate");event.preventDefault();loadScript(getVar("static-root-path")+getVar("settings-js"));setTimeout(()=>{const themes=getVar("themes").split(",");for(const theme of themes){if(theme!==""){preLoadCss(getVar("root-path")+theme+".css")}}},0)};window.searchState={loadingText:"Loading search results...",input:document.getElementsByClassName("search-input")[0],outputElement:()=>{let el=document.getElementById("search");if(!el){el=document.createElement("section");el.id="search";getNotDisplayedElem().appendChild(el)}return el},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:()=>{if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},isDisplayed:()=>searchState.outputElement().parentElement.id===ALTERNATIVE_DISPLAY_ID,focus:()=>{searchState.input.focus()},defocus:()=>{searchState.input.blur()},showResults:search=>{if(search===null||typeof search==="undefined"){search=searchState.outputElement()}switchDisplayedElement(search);searchState.mouseMovedAfterSearch=false;document.title=searchState.title},removeQueryParameters:()=>{document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.hash)}},hideResults:()=>{switchDisplayedElement(null);searchState.removeQueryParameters()},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=").map(x=>x.replace(/\+/g," "));params[decodeURIComponent(pair[0])]=typeof pair[1]==="undefined"?null:decodeURIComponent(pair[1])});return params},setup:()=>{const search_input=searchState.input;if(!searchState.input){return}let searchLoaded=false;function sendSearchForm(){document.getElementsByClassName("search-form")[0].submit()}function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(getVar("static-root-path")+getVar("search-js"),sendSearchForm);loadScript(resourcePath("search-index",".js"),sendSearchForm)}}search_input.addEventListener("focus",()=>{search_input.origPlaceholder=search_input.placeholder;search_input.placeholder="Type your search here.";loadSearch()});if(search_input.value!==""){loadSearch()}const params=searchState.getQueryStringParams();if(params.search!==undefined){searchState.setLoadingSearch();loadSearch()}},setLoadingSearch:()=>{const search=searchState.outputElement();search.innerHTML="

    "+searchState.loadingText+"

    ";searchState.showResults(search)},};const toggleAllDocsId="toggle-all-docs";let savedHash="";function handleHashes(ev){if(ev!==null&&searchState.isDisplayed()&&ev.newURL){switchDisplayedElement(null);const hash=ev.newURL.slice(ev.newURL.indexOf("#")+1);if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.search+"#"+hash)}const elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}const pageId=window.location.hash.replace(/^#/,"");if(savedHash!==pageId){savedHash=pageId;if(pageId!==""){expandSection(pageId)}}if(savedHash.startsWith("impl-")){const splitAt=savedHash.indexOf("/");if(splitAt!==-1){const implId=savedHash.slice(0,splitAt);const assocId=savedHash.slice(splitAt+1);const implElem=document.getElementById(implId);if(implElem&&implElem.parentElement.tagName==="SUMMARY"&&implElem.parentElement.parentElement.tagName==="DETAILS"){onEachLazy(implElem.parentElement.parentElement.querySelectorAll(`[id^="${assocId}"]`),item=>{const numbered=/([^-]+)-([0-9]+)/.exec(item.id);if(item.id===assocId||(numbered&&numbered[1]===assocId)){openParentDetails(item);item.scrollIntoView();setTimeout(()=>{window.location.replace("#"+item.id)},0)}})}}}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName==="DETAILS"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function handleEscape(ev){searchState.clearInputTimeout();searchState.hideResults();ev.preventDefault();searchState.defocus();window.hideAllModals(true)}function handleShortcut(ev){const disableShortcuts=getSettingValue("disable-shortcuts")==="true";if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName==="INPUT"&&document.activeElement.type!=="checkbox"&&document.activeElement.type!=="radio"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":ev.preventDefault();searchState.focus();break;case"+":ev.preventDefault();expandAllDocs();break;case"-":ev.preventDefault();collapseAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementsByClassName("sidebar-elems")[0];function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const modpath=hasClass(document.querySelector(".rustdoc"),"mod")?"../":"";const h3=document.createElement("h3");h3.innerHTML=`${longty}`;const ul=document.createElement("ul");ul.className="block "+shortty;for(const name of filtered){let path;if(shortty==="mod"){path=`${modpath}${name}/index.html`}else{path=`${modpath}${shortty}.${name}.html`}let current_page=document.location.href.toString();if(current_page.endsWith("/")){current_page+="index.html"}const link=document.createElement("a");link.href=path;if(path===current_page){link.className="current"}link.textContent=name;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}sidebar.appendChild(h3);sidebar.appendChild(ul)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Aliases");block("union","unions","Unions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");block("opaque","opaque-types","Opaque Types");block("attr","attributes","Attribute Macros");block("derive","derives","Derive Macros");block("traitalias","trait-aliases","Trait Aliases")}}window.register_implementors=imp=>{const implementors=document.getElementById("implementors-list");const synthetic_implementors=document.getElementById("synthetic-implementors-list");const inlined_types=new Set();const TEXT_IDX=0;const SYNTHETIC_IDX=1;const TYPES_IDX=2;if(synthetic_implementors){onEachLazy(synthetic_implementors.getElementsByClassName("impl"),el=>{const aliases=el.getAttribute("data-aliases");if(!aliases){return}aliases.split(",").forEach(alias=>{inlined_types.add(alias)})})}let currentNbImpls=implementors.getElementsByClassName("impl").length;const traitName=document.querySelector(".main-heading h1 > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const script=document.querySelector("script[data-ignore-extern-crates]");const ignoreExternCrates=new Set((script?script.getAttribute("data-ignore-extern-crates"):"").split(","));for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.has(lib)){continue}const structs=imp[lib];struct_loop:for(const struct of structs){const list=struct[SYNTHETIC_IDX]?synthetic_implementors:implementors;if(struct[SYNTHETIC_IDX]){for(const struct_type of struct[TYPES_IDX]){if(inlined_types.has(struct_type)){continue struct_loop}inlined_types.add(struct_type)}}const code=document.createElement("h3");code.innerHTML=struct[TEXT_IDX];addClass(code,"code-header");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});const currentId=baseIdName+currentNbImpls;const anchor=document.createElement("a");anchor.href="#"+currentId;addClass(anchor,"anchor");const display=document.createElement("div");display.id=currentId;addClass(display,"impl");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}window.register_type_impls=imp=>{if(!imp||!imp[window.currentCrate]){return}window.pending_type_impls=null;const idMap=new Map();let implementations=document.getElementById("implementations-list");let trait_implementations=document.getElementById("trait-implementations-list");let trait_implementations_header=document.getElementById("trait-implementations");const script=document.querySelector("script[data-self-path]");const selfPath=script?script.getAttribute("data-self-path"):null;const mainContent=document.querySelector("#main-content");const sidebarSection=document.querySelector(".sidebar section");let methods=document.querySelector(".sidebar .block.method");let associatedTypes=document.querySelector(".sidebar .block.associatedtype");let associatedConstants=document.querySelector(".sidebar .block.associatedconstant");let sidebarTraitList=document.querySelector(".sidebar .block.trait-implementation");for(const impList of imp[window.currentCrate]){const types=impList.slice(2);const text=impList[0];const isTrait=impList[1]!==0;const traitName=impList[1];if(types.indexOf(selfPath)===-1){continue}let outputList=isTrait?trait_implementations:implementations;if(outputList===null){const outputListName=isTrait?"Trait Implementations":"Implementations";const outputListId=isTrait?"trait-implementations-list":"implementations-list";const outputListHeaderId=isTrait?"trait-implementations":"implementations";const outputListHeader=document.createElement("h2");outputListHeader.id=outputListHeaderId;outputListHeader.innerText=outputListName;outputList=document.createElement("div");outputList.id=outputListId;if(isTrait){const link=document.createElement("a");link.href=`#${outputListHeaderId}`;link.innerText="Trait Implementations";const h=document.createElement("h3");h.appendChild(link);trait_implementations=outputList;trait_implementations_header=outputListHeader;sidebarSection.appendChild(h);sidebarTraitList=document.createElement("ul");sidebarTraitList.className="block trait-implementation";sidebarSection.appendChild(sidebarTraitList);mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}else{implementations=outputList;if(trait_implementations){mainContent.insertBefore(outputListHeader,trait_implementations_header);mainContent.insertBefore(outputList,trait_implementations_header)}else{const mainContent=document.querySelector("#main-content");mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}}}const template=document.createElement("template");template.innerHTML=text;onEachLazy(template.content.querySelectorAll("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});onEachLazy(template.content.querySelectorAll("[id]"),el=>{let i=0;if(idMap.has(el.id)){i=idMap.get(el.id)}else if(document.getElementById(el.id)){i=1;while(document.getElementById(`${el.id}-${2 * i}`)){i=2*i}while(document.getElementById(`${el.id}-${i}`)){i+=1}}if(i!==0){const oldHref=`#${el.id}`;const newHref=`#${el.id}-${i}`;el.id=`${el.id}-${i}`;onEachLazy(template.content.querySelectorAll("a[href]"),link=>{if(link.getAttribute("href")===oldHref){link.href=newHref}})}idMap.set(el.id,i+1)});const templateAssocItems=template.content.querySelectorAll("section.tymethod, "+"section.method, section.associatedtype, section.associatedconstant");if(isTrait){const li=document.createElement("li");const a=document.createElement("a");a.href=`#${template.content.querySelector(".impl").id}`;a.textContent=traitName;li.appendChild(a);sidebarTraitList.append(li)}else{onEachLazy(templateAssocItems,item=>{let block=hasClass(item,"associatedtype")?associatedTypes:(hasClass(item,"associatedconstant")?associatedConstants:(methods));if(!block){const blockTitle=hasClass(item,"associatedtype")?"Associated Types":(hasClass(item,"associatedconstant")?"Associated Constants":("Methods"));const blockClass=hasClass(item,"associatedtype")?"associatedtype":(hasClass(item,"associatedconstant")?"associatedconstant":("method"));const blockHeader=document.createElement("h3");const blockLink=document.createElement("a");blockLink.href="#implementations";blockLink.innerText=blockTitle;blockHeader.appendChild(blockLink);block=document.createElement("ul");block.className=`block ${blockClass}`;const insertionReference=methods||sidebarTraitList;if(insertionReference){const insertionReferenceH=insertionReference.previousElementSibling;sidebarSection.insertBefore(blockHeader,insertionReferenceH);sidebarSection.insertBefore(block,insertionReferenceH)}else{sidebarSection.appendChild(blockHeader);sidebarSection.appendChild(block)}if(hasClass(item,"associatedtype")){associatedTypes=block}else if(hasClass(item,"associatedconstant")){associatedConstants=block}else{methods=block}}const li=document.createElement("li");const a=document.createElement("a");a.innerText=item.id.split("-")[0].split(".")[1];a.href=`#${item.id}`;li.appendChild(a);block.appendChild(li)})}outputList.appendChild(template.content)}for(const list of[methods,associatedTypes,associatedConstants,sidebarTraitList]){if(!list){continue}const newChildren=Array.prototype.slice.call(list.children);newChildren.sort((a,b)=>{const aI=a.innerText;const bI=b.innerText;return aIbI?1:0});list.replaceChildren(...newChildren)}};if(window.pending_type_impls){window.register_type_impls(window.pending_type_impls)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementsByClassName("sidebar-elems")[0];if(!sidebarElems){return}const h3=document.createElement("h3");h3.innerHTML="Crates";const ul=document.createElement("ul");ul.className="block crate";for(const crate of window.ALL_CRATES){const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.textContent=crate;const li=document.createElement("li");if(window.rootPath!=="./"&&crate===window.currentCrate){li.className="current"}li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(h3);sidebarElems.appendChild(ul)}function expandAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hasClass(e,"type-contents-toggle")&&!hasClass(e,"more-examples-toggle")){e.open=true}});innerToggle.title="collapse all docs";innerToggle.children[0].innerText="\u2212"}function collapseAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});innerToggle.title="expand all docs";innerToggle.children[0].innerText="+"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}if(hasClass(innerToggle,"will-expand")){expandAllDocs()}else{collapseAllDocs()}}(function(){const toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}const hideMethodDocs=getSettingValue("auto-hide-method-docs")==="true";const hideImplementations=getSettingValue("auto-hide-trait-implementations")==="true";const hideLargeItemContents=getSettingValue("auto-hide-large-items")!=="false";function setImplementorsTogglesOpen(id,open){const list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName("implementors-toggle"),e=>{e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen("trait-implementations-list",false);setImplementorsTogglesOpen("blanket-implementations-list",false)}onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}})}());window.rustdoc_add_line_numbers_to_examples=()=>{onEachLazy(document.getElementsByClassName("rust-example-rendered"),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");if(line_numbers.length>0){return}const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{onEachLazy(document.getElementsByClassName("rust-example-rendered"),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");for(const node of line_numbers){parent.removeChild(node)}})};if(getSettingValue("line-numbers")==="true"){window.rustdoc_add_line_numbers_to_examples()}function showSidebar(){window.hideAllModals(false);const sidebar=document.getElementsByClassName("sidebar")[0];addClass(sidebar,"shown")}function hideSidebar(){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown")}window.addEventListener("resize",()=>{if(window.CURRENT_TOOLTIP_ELEMENT){const base=window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE;const force_visible=base.TOOLTIP_FORCE_VISIBLE;hideTooltip(false);if(force_visible){showTooltip(base);base.TOOLTIP_FORCE_VISIBLE=true}}});const mainElem=document.getElementById(MAIN_ID);if(mainElem){mainElem.addEventListener("click",hideSidebar)}onEachLazy(document.querySelectorAll("a[href^='#']"),el=>{el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})});onEachLazy(document.querySelectorAll(".toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});function showTooltip(e){const notable_ty=e.getAttribute("data-notable-ty");if(!window.NOTABLE_TRAITS&¬able_ty){const data=document.getElementById("notable-traits-data");if(data){window.NOTABLE_TRAITS=JSON.parse(data.innerText)}else{throw new Error("showTooltip() called with notable without any notable traits!")}}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE===e){clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);return}window.hideAllModals(false);const wrapper=document.createElement("div");if(notable_ty){wrapper.innerHTML="
    "+window.NOTABLE_TRAITS[notable_ty]+"
    "}else{if(e.getAttribute("title")!==null){e.setAttribute("data-title",e.getAttribute("title"));e.removeAttribute("title")}if(e.getAttribute("data-title")!==null){const titleContent=document.createElement("div");titleContent.className="content";titleContent.appendChild(document.createTextNode(e.getAttribute("data-title")));wrapper.appendChild(titleContent)}}wrapper.className="tooltip popover";const focusCatcher=document.createElement("div");focusCatcher.setAttribute("tabindex","0");focusCatcher.onfocus=hideTooltip;wrapper.appendChild(focusCatcher);const pos=e.getBoundingClientRect();wrapper.style.top=(pos.top+window.scrollY+pos.height)+"px";wrapper.style.left=0;wrapper.style.right="auto";wrapper.style.visibility="hidden";const body=document.getElementsByTagName("body")[0];body.appendChild(wrapper);const wrapperPos=wrapper.getBoundingClientRect();const finalPos=pos.left+window.scrollX-wrapperPos.width+24;if(finalPos>0){wrapper.style.left=finalPos+"px"}else{wrapper.style.setProperty("--popover-arrow-offset",(wrapperPos.right-pos.right+4)+"px")}wrapper.style.visibility="";window.CURRENT_TOOLTIP_ELEMENT=wrapper;window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE=e;clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);wrapper.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}clearTooltipHoverTimeout(e)};wrapper.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&!e.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(wrapper,"fade-out")}}}function setTooltipHoverTimeout(element,show){clearTooltipHoverTimeout(element);if(!show&&!window.CURRENT_TOOLTIP_ELEMENT){return}if(show&&window.CURRENT_TOOLTIP_ELEMENT){return}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE!==element){return}element.TOOLTIP_HOVER_TIMEOUT=setTimeout(()=>{if(show){showTooltip(element)}else if(!element.TOOLTIP_FORCE_VISIBLE){hideTooltip(false)}},show?window.RUSTDOC_TOOLTIP_HOVER_MS:window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS)}function clearTooltipHoverTimeout(element){if(element.TOOLTIP_HOVER_TIMEOUT!==undefined){removeClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out");clearTimeout(element.TOOLTIP_HOVER_TIMEOUT);delete element.TOOLTIP_HOVER_TIMEOUT}}function tooltipBlurHandler(event){if(window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.contains(event.relatedTarget)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(event.relatedTarget)){setTimeout(()=>hideTooltip(false),0)}}function hideTooltip(focus){if(window.CURRENT_TOOLTIP_ELEMENT){if(window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE){if(focus){window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.focus()}window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE=false}const body=document.getElementsByTagName("body")[0];body.removeChild(window.CURRENT_TOOLTIP_ELEMENT);clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);window.CURRENT_TOOLTIP_ELEMENT=null}}onEachLazy(document.getElementsByClassName("tooltip"),e=>{e.onclick=()=>{e.TOOLTIP_FORCE_VISIBLE=e.TOOLTIP_FORCE_VISIBLE?false:true;if(window.CURRENT_TOOLTIP_ELEMENT&&!e.TOOLTIP_FORCE_VISIBLE){hideTooltip(true)}else{showTooltip(e);window.CURRENT_TOOLTIP_ELEMENT.setAttribute("tabindex","0");window.CURRENT_TOOLTIP_ELEMENT.focus();window.CURRENT_TOOLTIP_ELEMENT.onblur=tooltipBlurHandler}return false};e.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointermove=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out")}}});const sidebar_menu_toggle=document.getElementsByClassName("sidebar-menu-toggle")[0];if(sidebar_menu_toggle){sidebar_menu_toggle.addEventListener("click",()=>{const sidebar=document.getElementsByClassName("sidebar")[0];if(!hasClass(sidebar,"shown")){showSidebar()}else{hideSidebar()}})}function helpBlurHandler(event){blurHandler(event,getHelpButton(),window.hidePopoverMenus)}function buildHelpMenu(){const book_info=document.createElement("span");const channel=getVar("channel");book_info.className="top";book_info.innerHTML=`You can find more information in \ +the rustdoc book.`;const shortcuts=[["?","Show this help dialog"],["S","Focus the search field"],["↑","Move up in search results"],["↓","Move down in search results"],["← / →","Switch result tab (when results focused)"],["⏎","Go to active search result"],["+","Expand all sections"],["-","Collapse all sections"],].map(x=>"
    "+x[0].split(" ").map((y,index)=>((index&1)===0?""+y+"":" "+y+" ")).join("")+"
    "+x[1]+"
    ").join("");const div_shortcuts=document.createElement("div");addClass(div_shortcuts,"shortcuts");div_shortcuts.innerHTML="

    Keyboard Shortcuts

    "+shortcuts+"
    ";const infos=[`For a full list of all search features, take a look here.`,"Prefix searches with a type followed by a colon (e.g., fn:) to \ + restrict the search to a given item kind.","Accepted kinds are: fn, mod, struct, \ + enum, trait, type, macro, \ + and const.","Search functions by type signature (e.g., vec -> usize or \ + -> vec or String, enum:Cow -> bool)","You can look for items with an exact name by putting double quotes around \ + your request: \"string\"","Look for functions that accept or return \ + slices and \ + arrays by writing \ + square brackets (e.g., -> [u8] or [] -> Option)","Look for items inside another one by searching for a path: vec::Vec",].map(x=>"

    "+x+"

    ").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="

    Search Tricks

    "+infos;const rustdoc_version=document.createElement("span");rustdoc_version.className="bottom";const rustdoc_version_code=document.createElement("code");rustdoc_version_code.innerText="rustdoc "+getVar("rustdoc-version");rustdoc_version.appendChild(rustdoc_version_code);const container=document.createElement("div");if(!isHelpPage){container.className="popover"}container.id="help";container.style.display="none";const side_by_side=document.createElement("div");side_by_side.className="side-by-side";side_by_side.appendChild(div_shortcuts);side_by_side.appendChild(div_infos);container.appendChild(book_info);container.appendChild(side_by_side);container.appendChild(rustdoc_version);if(isHelpPage){const help_section=document.createElement("section");help_section.appendChild(container);document.getElementById("main-content").appendChild(help_section);container.style.display="block"}else{const help_button=getHelpButton();help_button.appendChild(container);container.onblur=helpBlurHandler;help_button.onblur=helpBlurHandler;help_button.children[0].onblur=helpBlurHandler}return container}window.hideAllModals=switchFocus=>{hideSidebar();window.hidePopoverMenus();hideTooltip(switchFocus)};window.hidePopoverMenus=()=>{onEachLazy(document.querySelectorAll(".search-form .popover"),elem=>{elem.style.display="none"})};function getHelpMenu(buildNeeded){let menu=getHelpButton().querySelector(".popover");if(!menu&&buildNeeded){menu=buildHelpMenu()}return menu}function showHelp(){getHelpButton().querySelector("a").focus();const menu=getHelpMenu(true);if(menu.style.display==="none"){window.hideAllModals();menu.style.display=""}}if(isHelpPage){showHelp();document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click",event=>{const target=event.target;if(target.tagName!=="A"||target.parentElement.id!==HELP_BUTTON_ID||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault()})}else{document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click",event=>{const target=event.target;if(target.tagName!=="A"||target.parentElement.id!==HELP_BUTTON_ID||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault();const menu=getHelpMenu(true);const shouldShowHelp=menu.style.display==="none";if(shouldShowHelp){showHelp()}else{window.hidePopoverMenus()}})}setMobileTopbar();addSidebarItems();addSidebarCrates();onHashChange(null);window.addEventListener("hashchange",onHashChange);searchState.setup()}());(function(){const SIDEBAR_MIN=100;const SIDEBAR_MAX=500;const RUSTDOC_MOBILE_BREAKPOINT=700;const BODY_MIN=400;const SIDEBAR_VANISH_THRESHOLD=SIDEBAR_MIN/2;const sidebarButton=document.getElementById("sidebar-button");if(sidebarButton){sidebarButton.addEventListener("click",e=>{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false");if(document.querySelector(".rustdoc.src")){window.rustdocToggleSrcSidebar()}e.preventDefault()})}let currentPointerId=null;let desiredSidebarSize=null;let pendingSidebarResizingFrame=false;const resizer=document.querySelector(".sidebar-resizer");const sidebar=document.querySelector(".sidebar");if(!resizer||!sidebar){return}const isSrcPage=hasClass(document.body,"src");function hideSidebar(){if(isSrcPage){window.rustdocCloseSourceSidebar();updateLocalStorage("src-sidebar-width",null);document.documentElement.style.removeProperty("--src-sidebar-width");sidebar.style.removeProperty("--src-sidebar-width");resizer.style.removeProperty("--src-sidebar-width")}else{addClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","true");updateLocalStorage("desktop-sidebar-width",null);document.documentElement.style.removeProperty("--desktop-sidebar-width");sidebar.style.removeProperty("--desktop-sidebar-width");resizer.style.removeProperty("--desktop-sidebar-width")}}function showSidebar(){if(isSrcPage){window.rustdocShowSourceSidebar()}else{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false")}}function changeSidebarSize(size){if(isSrcPage){updateLocalStorage("src-sidebar-width",size);sidebar.style.setProperty("--src-sidebar-width",size+"px");resizer.style.setProperty("--src-sidebar-width",size+"px")}else{updateLocalStorage("desktop-sidebar-width",size);sidebar.style.setProperty("--desktop-sidebar-width",size+"px");resizer.style.setProperty("--desktop-sidebar-width",size+"px")}}function isSidebarHidden(){return isSrcPage?!hasClass(document.documentElement,"src-sidebar-expanded"):hasClass(document.documentElement,"hide-sidebar")}function resize(e){if(currentPointerId===null||currentPointerId!==e.pointerId){return}e.preventDefault();const pos=e.clientX-3;if(pos=SIDEBAR_MIN){if(isSidebarHidden()){showSidebar()}const constrainedPos=Math.min(pos,window.innerWidth-BODY_MIN,SIDEBAR_MAX);changeSidebarSize(constrainedPos);desiredSidebarSize=constrainedPos;if(pendingSidebarResizingFrame!==false){clearTimeout(pendingSidebarResizingFrame)}pendingSidebarResizingFrame=setTimeout(()=>{if(currentPointerId===null||pendingSidebarResizingFrame===false){return}pendingSidebarResizingFrame=false;document.documentElement.style.setProperty("--resizing-sidebar-width",desiredSidebarSize+"px")},100)}}window.addEventListener("resize",()=>{if(window.innerWidth=(window.innerWidth-BODY_MIN)){changeSidebarSize(window.innerWidth-BODY_MIN)}else if(desiredSidebarSize!==null&&desiredSidebarSize>SIDEBAR_MIN){changeSidebarSize(desiredSidebarSize)}});function stopResize(e){if(currentPointerId===null){return}if(e){e.preventDefault()}desiredSidebarSize=sidebar.getBoundingClientRect().width;removeClass(resizer,"active");window.removeEventListener("pointermove",resize,false);window.removeEventListener("pointerup",stopResize,false);removeClass(document.documentElement,"sidebar-resizing");document.documentElement.style.removeProperty("--resizing-sidebar-width");if(resizer.releasePointerCapture){resizer.releasePointerCapture(currentPointerId);currentPointerId=null}}function initResize(e){if(currentPointerId!==null||e.altKey||e.ctrlKey||e.metaKey||e.button!==0){return}if(resizer.setPointerCapture){resizer.setPointerCapture(e.pointerId);if(!resizer.hasPointerCapture(e.pointerId)){resizer.releasePointerCapture(e.pointerId);return}currentPointerId=e.pointerId}window.hideAllModals(false);e.preventDefault();window.addEventListener("pointermove",resize,false);window.addEventListener("pointercancel",stopResize,false);window.addEventListener("pointerup",stopResize,false);addClass(resizer,"active");addClass(document.documentElement,"sidebar-resizing");const pos=e.clientX-sidebar.offsetLeft-3;document.documentElement.style.setProperty("--resizing-sidebar-width",pos+"px");desiredSidebarSize=null}resizer.addEventListener("pointerdown",initResize,false)}());(function(){let reset_button_timeout=null;const but=document.getElementById("copy-path");if(!but){return}but.onclick=()=>{const parent=but.parentElement;const path=[];onEach(parent.childNodes,child=>{if(child.tagName==="A"){path.push(child.textContent)}});const el=document.createElement("textarea");el.value=path.join("::");el.setAttribute("readonly","");el.style.position="absolute";el.style.left="-9999px";document.body.appendChild(el);el.select();document.execCommand("copy");document.body.removeChild(el);but.children[0].style.display="none";let tmp;if(but.childNodes.length<2){tmp=document.createTextNode("✓");but.appendChild(tmp)}else{onEachLazy(but.childNodes,e=>{if(e.nodeType===Node.TEXT_NODE){tmp=e;return true}});tmp.textContent="✓"}if(reset_button_timeout!==null){window.clearTimeout(reset_button_timeout)}function reset_button(){tmp.textContent="";reset_button_timeout=null;but.children[0].style.display=""}reset_button_timeout=window.setTimeout(reset_button,1000)}}()) \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/normalize-76eba96aa4d2e634.css b/Documentation/RustDoc/static.files/normalize-76eba96aa4d2e634.css new file mode 100644 index 00000000..469959f1 --- /dev/null +++ b/Documentation/RustDoc/static.files/normalize-76eba96aa4d2e634.css @@ -0,0 +1,2 @@ + /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ +html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:0.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type="button"],[type="reset"],[type="submit"],button{-webkit-appearance:button}[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/noscript-04d5337699b92874.css b/Documentation/RustDoc/static.files/noscript-04d5337699b92874.css new file mode 100644 index 00000000..fbd55f57 --- /dev/null +++ b/Documentation/RustDoc/static.files/noscript-04d5337699b92874.css @@ -0,0 +1 @@ + #main-content .attributes{margin-left:0 !important;}#copy-path,#sidebar-button,.sidebar-resizer{display:none !important;}nav.sub{display:none;}.src .sidebar{display:none;}.notable-traits{display:none;}:root{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--test-arrow-color:#f5f5f5;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#f5f5f5;--test-arrow-hover-background-color:rgb(78,139,202);--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}@media (prefers-color-scheme:dark){:root{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--test-arrow-color:#dedede;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#dedede;--test-arrow-hover-background-color:#4e8bca;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}} \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/rust-logo-151179464ae7ed46.svg b/Documentation/RustDoc/static.files/rust-logo-151179464ae7ed46.svg new file mode 100644 index 00000000..62424d8f --- /dev/null +++ b/Documentation/RustDoc/static.files/rust-logo-151179464ae7ed46.svg @@ -0,0 +1,61 @@ + + + diff --git a/Documentation/RustDoc/static.files/rustdoc-e935ef01ae1c1829.css b/Documentation/RustDoc/static.files/rustdoc-e935ef01ae1c1829.css new file mode 100644 index 00000000..37ac48cc --- /dev/null +++ b/Documentation/RustDoc/static.files/rustdoc-e935ef01ae1c1829.css @@ -0,0 +1,24 @@ + :root{--nav-sub-mobile-padding:8px;--search-typename-width:6.75rem;--desktop-sidebar-width:200px;--src-sidebar-width:300px;--desktop-sidebar-z-index:100;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular-018c141bf0843ffd.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:500;src:local('Fira Sans Medium'),url("FiraSans-Medium-8f9a781e4970d388.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:400;src:local('Source Serif 4'),url("SourceSerif4-Regular-46f98efaafac5295.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:italic;font-weight:400;src:local('Source Serif 4 Italic'),url("SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:700;src:local('Source Serif 4 Bold'),url("SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{box-sizing:border-box;}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;font-feature-settings:"kern","liga";background-color:var(--main-background-color);color:var(--main-color);}h1{font-size:1.5rem;}h2{font-size:1.375rem;}h3{font-size:1.25rem;}h1,h2,h3,h4,h5,h6{font-weight:500;}h1,h2,h3,h4{margin:25px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}.docblock>h2:first-child,.docblock>h3:first-child,.docblock>h4:first-child,.docblock>h5:first-child,.docblock>h6:first-child{margin-top:0;}.main-heading h1{margin:0;padding:0;flex-grow:1;overflow-wrap:break-word;overflow-wrap:anywhere;}.main-heading{display:flex;flex-wrap:wrap;padding-bottom:6px;margin-bottom:15px;}.content h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h1,h2{line-height:1.25;padding-top:3px;padding-bottom:9px;}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;margin:0;padding:0;white-space:pre-wrap;}#crate-search,h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,.search-input,.search-results .result-name,.item-name>a,.out-of-band,span.since,a.src,#help-button>a,summary.hideme,.scraped-example-list,ul.all-items{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}#toggle-all-docs,a.anchor,.section-header a,#src-sidebar a,.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,h1 a,.search-results a,.stab,.result-name i{color:var(--main-color);}span.enum,a.enum,span.struct,a.struct,span.union,a.union,span.primitive,a.primitive,span.type,a.type,span.foreigntype,a.foreigntype{color:var(--type-link-color);}span.trait,a.trait,span.traitalias,a.traitalias{color:var(--trait-link-color);}span.associatedtype,a.associatedtype,span.constant,a.constant,span.static,a.static{color:var(--assoc-item-link-color);}span.fn,a.fn,span.method,a.method,span.tymethod,a.tymethod{color:var(--function-link-color);}span.attr,a.attr,span.derive,a.derive,span.macro,a.macro{color:var(--macro-link-color);}span.mod,a.mod{color:var(--mod-link-color);}span.keyword,a.keyword{color:var(--keyword-link-color);}a{color:var(--link-color);text-decoration:none;}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p,.docblock>.warning{margin:0 0 .75em 0;}p:last-child,.docblock>.warning:last-child{margin:0;}button{padding:1px 6px;cursor:pointer;}button#toggle-all-docs{padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.src main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}details:not(.toggle) summary{margin-bottom:.6em;}code,pre,a.test-arrow,.code-header{font-family:"Source Code Pro",monospace;}.docblock code,.docblock-short code{border-radius:3px;padding:0 0.125em;}.docblock pre code,.docblock-short pre code{padding:0;}pre{padding:14px;line-height:1.5;}pre.item-decl{overflow-x:auto;}.item-decl .type-contents-toggle{contain:initial;}.src .content pre{padding:20px;}.rustdoc.src .example-wrap pre.src-line-numbers{padding:20px 0 20px 4px;}img{max-width:100%;}.logo-container{line-height:0;display:block;}.rust-logo{filter:var(--rust-logo-filter);}.sidebar{font-size:0.875rem;flex:0 0 var(--desktop-sidebar-width);width:var(--desktop-sidebar-width);overflow-y:scroll;overscroll-behavior:contain;position:sticky;height:100vh;top:0;left:0;z-index:var(--desktop-sidebar-z-index);}.rustdoc.src .sidebar{flex-basis:50px;width:50px;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.hide-sidebar .sidebar,.hide-sidebar .sidebar-resizer{display:none;}.sidebar-resizer{touch-action:none;width:9px;cursor:col-resize;z-index:calc(var(--desktop-sidebar-z-index) + 1);position:fixed;height:100%;left:calc(var(--desktop-sidebar-width) + 1px);}.rustdoc.src .sidebar-resizer{left:49px;}.src-sidebar-expanded .src .sidebar-resizer{left:var(--src-sidebar-width);}.sidebar-resizing{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;}.sidebar-resizing*{cursor:col-resize !important;}.sidebar-resizing .sidebar{position:fixed;}.sidebar-resizing>body{padding-left:var(--resizing-sidebar-width);}.sidebar-resizer:hover,.sidebar-resizer:active,.sidebar-resizer:focus,.sidebar-resizer.active{width:10px;margin:0;left:var(--desktop-sidebar-width);border-left:solid 1px var(--sidebar-resizer-hover);}.src-sidebar-expanded .rustdoc.src .sidebar-resizer:hover,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:active,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:focus,.src-sidebar-expanded .rustdoc.src .sidebar-resizer.active{left:calc(var(--src-sidebar-width) - 1px);}@media (pointer:coarse){.sidebar-resizer{display:none !important;}}.sidebar-resizer.active{padding:0 140px;width:2px;margin-left:-140px;border-left:none;}.sidebar-resizer.active:before{border-left:solid 2px var(--sidebar-resizer-active);display:block;height:100%;content:"";}.sidebar,.mobile-topbar,.sidebar-menu-toggle,#src-sidebar{background-color:var(--sidebar-background-color);}.src .sidebar>*{visibility:hidden;}.src-sidebar-expanded .src .sidebar{overflow-y:auto;flex-basis:var(--src-sidebar-width);width:var(--src-sidebar-width);}.src-sidebar-expanded .src .sidebar>*{visibility:visible;}#all-types{margin-top:1em;}*{scrollbar-width:initial;scrollbar-color:var(--scrollbar-color);}.sidebar{scrollbar-width:thin;scrollbar-color:var(--scrollbar-color);}::-webkit-scrollbar{width:12px;}.sidebar::-webkit-scrollbar{width:8px;}::-webkit-scrollbar-track{-webkit-box-shadow:inset 0;background-color:var(--scrollbar-track-background-color);}.sidebar::-webkit-scrollbar-track{background-color:var(--scrollbar-track-background-color);}::-webkit-scrollbar-thumb,.sidebar::-webkit-scrollbar-thumb{background-color:var(--scrollbar-thumb-background-color);}.hidden{display:none !important;}.logo-container>img{height:48px;width:48px;}ul.block,.block li{padding:0;margin:0;list-style:none;}.sidebar-elems a,.sidebar>h2 a{display:block;padding:0.25rem;margin-left:-0.25rem;margin-right:0.25rem;}.sidebar h2{overflow-wrap:anywhere;padding:0;margin:0.7rem 0;}.sidebar h3{font-size:1.125rem;padding:0;margin:0;}.sidebar-elems,.sidebar>.version,.sidebar>h2{padding-left:24px;}.sidebar a{color:var(--sidebar-link-color);}.sidebar .current,.sidebar .current a,.sidebar-crate a.logo-container:hover+h2 a,.sidebar a:hover:not(.logo-container){background-color:var(--sidebar-current-link-background-color);}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;}.sidebar-crate{display:flex;align-items:center;justify-content:center;margin:14px 32px 1rem;row-gap:10px;column-gap:32px;flex-wrap:wrap;}.sidebar-crate h2{flex-grow:1;margin:0 -8px;align-self:start;}.sidebar-crate .logo-container{margin:0 -16px 0 -16px;text-align:center;}.sidebar-crate h2 a{display:block;margin:0 calc(-24px + 0.25rem) 0 -0.2rem;padding:calc((16px - 0.57rem ) / 2 ) 0.25rem;padding-left:0.2rem;}.sidebar-crate h2 .version{display:block;font-weight:normal;font-size:1rem;overflow-wrap:break-word;}.sidebar-crate+.version{margin-top:-1rem;margin-bottom:1rem;}.mobile-topbar{display:none;}.rustdoc .example-wrap{display:flex;position:relative;margin-bottom:10px;}.rustdoc .example-wrap:last-child{margin-bottom:0px;}.rustdoc .example-wrap pre{margin:0;flex-grow:1;}.rustdoc:not(.src) .example-wrap pre{overflow:auto hidden;}.rustdoc .example-wrap pre.example-line-numbers,.rustdoc .example-wrap pre.src-line-numbers{flex-grow:0;min-width:fit-content;overflow:initial;text-align:right;-webkit-user-select:none;user-select:none;padding:14px 8px;color:var(--src-line-numbers-span-color);}.rustdoc .example-wrap pre.src-line-numbers{padding:14px 0;}.src-line-numbers a,.src-line-numbers span{color:var(--src-line-numbers-span-color);padding:0 8px;}.src-line-numbers :target{background-color:transparent;border-right:none;padding:0 8px;}.src-line-numbers .line-highlighted{background-color:var(--src-line-number-highlighted-background-color);}.search-loading{text-align:center;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock :not(pre)>code,.docblock-short code{white-space:pre-wrap;}.top-doc .docblock h2{font-size:1.375rem;}.top-doc .docblock h3{font-size:1.25rem;}.top-doc .docblock h4,.top-doc .docblock h5{font-size:1.125rem;}.top-doc .docblock h6{font-size:1rem;}.docblock h5{font-size:1rem;}.docblock h6{font-size:0.875rem;}.docblock{margin-left:24px;position:relative;}.docblock>:not(.more-examples-toggle):not(.example-wrap){max-width:100%;overflow-x:auto;}.out-of-band{flex-grow:0;font-size:1.125rem;}.docblock code,.docblock-short code,pre,.rustdoc.src .example-wrap{background-color:var(--code-block-background-color);}#main-content{position:relative;}.docblock table{margin:.5em 0;border-collapse:collapse;}.docblock table td,.docblock table th{padding:.5em;border:1px solid var(--border-color);}.docblock table tbody tr:nth-child(2n){background:var(--table-alt-row-background-color);}div.where{white-space:pre-wrap;font-size:0.875rem;}.item-info{display:block;margin-left:24px;}.item-info code{font-size:0.875rem;}#main-content>.item-info{margin-left:0;}nav.sub{flex-grow:1;flex-flow:row nowrap;margin:4px 0 25px 0;display:flex;align-items:center;}.search-form{position:relative;display:flex;height:34px;flex-grow:1;}.src nav.sub{margin:0 0 15px 0;}.section-header{display:block;position:relative;}.section-header:hover>.anchor,.impl:hover>.anchor,.trait-impl:hover>.anchor,.variant:hover>.anchor{display:initial;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.section-header>.anchor{left:-15px;padding-right:8px;}h2.section-header>.anchor{padding-right:6px;}a.doc-anchor{color:var(--main-color);display:none;position:absolute;left:-17px;padding-right:5px;padding-left:3px;}*:hover>.doc-anchor{display:block;}.top-doc>.docblock>*:first-child>.doc-anchor{display:none !important;}.main-heading a:hover,.example-wrap .rust a:hover,.all-items a:hover,.docblock a:not(.test-arrow):not(.scrape-help):not(.tooltip):hover:not(.doc-anchor),.docblock-short a:not(.test-arrow):not(.scrape-help):not(.tooltip):hover,.item-info a{text-decoration:underline;}.crate.block li.current a{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;padding:0;margin:0;}.item-table>li{display:table-row;}.item-table>li>div{display:table-cell;}.item-table>li>.item-name{padding-right:1.25rem;}.search-results-title{margin-top:0;white-space:nowrap;display:flex;align-items:baseline;}#crate-search-div{position:relative;min-width:5em;}#crate-search{min-width:115px;padding:0 23px 0 4px;max-width:100%;text-overflow:ellipsis;border:1px solid var(--border-color);border-radius:4px;outline:none;cursor:pointer;-moz-appearance:none;-webkit-appearance:none;text-indent:0.01px;background-color:var(--main-background-color);color:inherit;line-height:1.5;font-weight:500;}#crate-search:hover,#crate-search:focus{border-color:var(--crate-search-hover-border);}#crate-search-div::after{pointer-events:none;width:100%;height:100%;position:absolute;top:0;left:0;content:"";background-repeat:no-repeat;background-size:20px;background-position:calc(100% - 2px) 56%;background-image:url('data:image/svg+xml, \ + ');filter:var(--crate-search-div-filter);}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:var(--crate-search-div-hover-filter);}#crate-search>option{font-size:1rem;}.search-input{-webkit-appearance:none;outline:none;border:1px solid var(--border-color);border-radius:2px;padding:8px;font-size:1rem;flex-grow:1;background-color:var(--button-background-color);color:var(--search-color);}.search-input:focus{border-color:var(--search-input-focused-border-color);}.search-results{display:none;}.search-results.active{display:block;}.search-results>a{display:flex;margin-left:2px;margin-right:2px;border-bottom:1px solid var(--search-result-border-color);gap:1em;}.search-results>a>div.desc{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;flex:2;}.search-results a:hover,.search-results a:focus{background-color:var(--search-result-link-focus-background-color);}.search-results .result-name{display:flex;align-items:center;justify-content:start;flex:3;}.search-results .result-name .alias{color:var(--search-results-alias-color);}.search-results .result-name .grey{color:var(--search-results-grey-color);}.search-results .result-name .typename{color:var(--search-results-grey-color);font-size:0.875rem;width:var(--search-typename-width);}.search-results .result-name .path{word-break:break-all;max-width:calc(100% - var(--search-typename-width));display:inline-block;}.search-results .result-name .path>*{display:inline;}.popover{position:absolute;top:100%;right:0;z-index:calc(var(--desktop-sidebar-z-index) + 1);margin-top:7px;border-radius:3px;border:1px solid var(--border-color);background-color:var(--main-background-color);color:var(--main-color);--popover-arrow-offset:11px;}.popover::before{content:'';position:absolute;right:var(--popover-arrow-offset);border:solid var(--border-color);border-width:1px 1px 0 0;background-color:var(--main-background-color);padding:4px;transform:rotate(-45deg);top:-5px;}.setting-line{margin:1.2em 0.6em;}.setting-radio input,.setting-check input{margin-right:0.3em;height:1.2rem;width:1.2rem;border:2px solid var(--settings-input-border-color);outline:none;-webkit-appearance:none;cursor:pointer;}.setting-radio input{border-radius:50%;}.setting-radio span,.setting-check span{padding-bottom:1px;}.setting-radio{margin-top:0.1em;margin-bottom:0.1em;min-width:3.8em;padding:0.3em;display:inline-flex;align-items:center;cursor:pointer;}.setting-radio+.setting-radio{margin-left:0.5em;}.setting-check{margin-right:20px;display:flex;align-items:center;cursor:pointer;}.setting-radio input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-check input:checked{background-color:var(--settings-input-color);border-width:1px;content:url('data:image/svg+xml,\ + \ + ');}.setting-radio input:focus,.setting-check input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-radio input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-radio input:hover,.setting-check input:hover{border-color:var(--settings-input-color) !important;}#help.popover{max-width:600px;--popover-arrow-offset:48px;}#help dt{float:left;clear:left;margin-right:0.5rem;}#help span.top,#help span.bottom{text-align:center;display:block;font-size:1.125rem;}#help span.top{margin:10px 0;border-bottom:1px solid var(--border-color);padding-bottom:4px;margin-bottom:6px;}#help span.bottom{clear:both;border-top:1px solid var(--border-color);}.side-by-side>div{width:50%;float:left;padding:0 20px 20px 17px;}.item-info .stab{display:block;padding:3px;margin-bottom:5px;}.item-name .stab{margin-left:0.3125em;}.stab{padding:0 2px;font-size:0.875rem;font-weight:normal;color:var(--main-color);background-color:var(--stab-background-color);width:fit-content;white-space:pre-wrap;border-radius:3px;display:inline;vertical-align:baseline;}.stab.portability>code{background:none;color:var(--stab-code-color);}.stab .emoji,.item-info .stab::before{font-size:1.25rem;}.stab .emoji{margin-right:0.3rem;}.item-info .stab::before{content:"\0";width:0;display:inline-block;color:transparent;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;float:right;}.rightside:not(a),.out-of-band{color:var(--right-side-color);}pre.rust{tab-size:4;-moz-tab-size:4;}pre.rust .kw{color:var(--code-highlight-kw-color);}pre.rust .kw-2{color:var(--code-highlight-kw-2-color);}pre.rust .lifetime{color:var(--code-highlight-lifetime-color);}pre.rust .prelude-ty{color:var(--code-highlight-prelude-color);}pre.rust .prelude-val{color:var(--code-highlight-prelude-val-color);}pre.rust .string{color:var(--code-highlight-string-color);}pre.rust .number{color:var(--code-highlight-number-color);}pre.rust .bool-val{color:var(--code-highlight-literal-color);}pre.rust .self{color:var(--code-highlight-self-color);}pre.rust .attr{color:var(--code-highlight-attribute-color);}pre.rust .macro,pre.rust .macro-nonterminal{color:var(--code-highlight-macro-color);}pre.rust .question-mark{font-weight:bold;color:var(--code-highlight-question-mark-color);}pre.rust .comment{color:var(--code-highlight-comment-color);}pre.rust .doccomment{color:var(--code-highlight-doc-comment-color);}.rustdoc.src .example-wrap pre.rust a{background:var(--codeblock-link-background);}.example-wrap.compile_fail,.example-wrap.should_panic{border-left:2px solid var(--codeblock-error-color);}.ignore.example-wrap{border-left:2px solid var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover,.example-wrap.should_panic:hover{border-left:2px solid var(--codeblock-error-hover-color);}.example-wrap.ignore:hover{border-left:2px solid var(--codeblock-ignore-hover-color);}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip{color:var(--codeblock-error-color);}.example-wrap.ignore .tooltip{color:var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover .tooltip,.example-wrap.should_panic:hover .tooltip{color:var(--codeblock-error-hover-color);}.example-wrap.ignore:hover .tooltip{color:var(--codeblock-ignore-hover-color);}.example-wrap .tooltip{position:absolute;display:block;left:-25px;top:5px;margin:0;line-height:1;}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip,.example-wrap.ignore .tooltip{font-weight:bold;font-size:1.25rem;}.content .docblock .warning{border-left:2px solid var(--warning-border-color);padding:14px;position:relative;overflow-x:visible !important;}.content .docblock .warning::before{color:var(--warning-border-color);content:"ⓘ";position:absolute;left:-25px;top:5px;font-weight:bold;font-size:1.25rem;}.top-doc>.docblock>.warning:first-child::before{top:20px;}a.test-arrow{visibility:hidden;position:absolute;padding:5px 10px 5px 10px;border-radius:5px;font-size:1.375rem;top:5px;right:5px;z-index:1;color:var(--test-arrow-color);background-color:var(--test-arrow-background-color);}a.test-arrow:hover{color:var(--test-arrow-hover-color);background-color:var(--test-arrow-hover-background-color);}.example-wrap:hover .test-arrow{visibility:visible;}.code-attribute{font-weight:300;color:var(--code-attribute-color);}.item-spacer{width:100%;height:12px;display:block;}.out-of-band>span.since{font-size:1.25rem;}.sub-variant h4{font-size:1rem;font-weight:400;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}:target{padding-right:3px;background-color:var(--target-background-color);border-right:3px solid var(--target-border-color);}.code-header a.tooltip{color:inherit;margin-right:15px;position:relative;}.code-header a.tooltip:hover{color:var(--link-color);}a.tooltip:hover::after{position:absolute;top:calc(100% - 10px);left:-15px;right:-15px;height:20px;content:"\00a0";}.fade-out{opacity:0;transition:opacity 0.45s cubic-bezier(0,0,0.1,1.0);}.popover.tooltip .content{margin:0.25em 0.5em;}.popover.tooltip .content pre,.popover.tooltip .content code{background:transparent;margin:0;padding:0;font-size:1.25rem;white-space:pre-wrap;}.popover.tooltip .content>h3:first-child{margin:0 0 5px 0;}.search-failed{text-align:center;margin-top:20px;display:none;}.search-failed.active{display:block;}.search-failed>ul{text-align:left;max-width:570px;margin-left:auto;margin-right:auto;}#search-tabs{display:flex;flex-direction:row;gap:1px;margin-bottom:4px;}#search-tabs button{text-align:center;font-size:1.125rem;border:0;border-top:2px solid;flex:1;line-height:1.5;color:inherit;}#search-tabs button:not(.selected){background-color:var(--search-tab-button-not-selected-background);border-top-color:var(--search-tab-button-not-selected-border-top-color);}#search-tabs button:hover,#search-tabs button.selected{background-color:var(--search-tab-button-selected-background);border-top-color:var(--search-tab-button-selected-border-top-color);}#search-tabs .count{font-size:1rem;font-variant-numeric:tabular-nums;color:var(--search-tab-title-count-color);}#search .error code{border-radius:3px;background-color:var(--search-error-code-background-color);}.search-corrections{font-weight:normal;}#src-sidebar{width:100%;overflow:auto;}#src-sidebar div.files>a:hover,details.dir-entry summary:hover,#src-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:var(--src-sidebar-background-hover);}#src-sidebar div.files>a.selected{background-color:var(--src-sidebar-background-selected);}.src-sidebar-title{position:sticky;top:0;display:flex;padding:8px 8px 0 48px;margin-bottom:7px;background:var(--sidebar-background-color);border-bottom:1px solid var(--border-color);}#settings-menu,#help-button{margin-left:4px;display:flex;}#sidebar-button{display:none;line-height:0;}.hide-sidebar #sidebar-button,.src #sidebar-button{display:flex;margin-right:4px;position:fixed;left:6px;height:34px;width:34px;background-color:var(--main-background-color);z-index:1;}.src #sidebar-button{left:8px;z-index:calc(var(--desktop-sidebar-z-index) + 1);}.hide-sidebar .src #sidebar-button{position:static;}#settings-menu>a,#help-button>a,#sidebar-button>a{display:flex;align-items:center;justify-content:center;background-color:var(--button-background-color);border:1px solid var(--border-color);border-radius:2px;color:var(--settings-button-color);font-size:20px;width:33px;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>a:hover,#help-button>a:focus,#sidebar-button>a:hover,#sidebar-button>a:focus{border-color:var(--settings-button-border-focus);}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}#copy-path{color:var(--copy-path-button-color);background:var(--main-background-color);height:34px;margin-left:10px;padding:0;padding-left:2px;border:0;width:33px;}#copy-path>img{filter:var(--copy-path-img-filter);}#copy-path:hover>img{filter:var(--copy-path-img-hover-filter);}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}kbd{display:inline-block;padding:3px 5px;font:15px monospace;line-height:10px;vertical-align:middle;border:solid 1px var(--border-color);border-radius:3px;color:var(--kbd-color);background-color:var(--kbd-background);box-shadow:inset 0 -1px 0 var(--kbd-box-shadow-color);}ul.all-items>li{list-style:none;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 -4px;padding:0 0 0 4px;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.toggle{contain:layout;position:relative;}details.toggle>summary.hideme{cursor:pointer;font-size:1rem;}details.toggle>summary{list-style:none;outline:none;}details.toggle>summary::-webkit-details-marker,details.toggle>summary::marker{display:none;}details.toggle>summary.hideme>span{margin-left:9px;}details.toggle>summary::before{background:url('data:image/svg+xml,') no-repeat top left;content:"";cursor:pointer;width:16px;height:16px;display:inline-block;vertical-align:middle;opacity:.5;filter:var(--toggle-filter);}details.toggle>summary.hideme>span,.more-examples-toggle summary,.more-examples-toggle .hide-more{color:var(--toggles-color);}details.toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.toggle>summary.hideme::after{content:"";}details.toggle>summary:focus::before,details.toggle>summary:hover::before{opacity:1;}details.toggle>summary:focus-visible::before{outline:1px dotted #000;outline-offset:1px;}details.non-exhaustive{margin-bottom:8px;}details.toggle>summary.hideme::before{position:relative;}details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.toggle[open] >summary.hideme{position:absolute;}details.toggle[open] >summary.hideme>span{display:none;}details.toggle[open] >summary::before{background:url('data:image/svg+xml,') no-repeat top left;}details.toggle[open] >summary::after{content:"Collapse";}.docblock summary>*{display:inline-block;}.docblock>.example-wrap:first-child .tooltip{margin-top:16px;}.src #sidebar-button>a:before,.sidebar-menu-toggle:before{content:url('data:image/svg+xml,\ + ');opacity:0.75;}.sidebar-menu-toggle:hover:before,.sidebar-menu-toggle:active:before,.sidebar-menu-toggle:focus:before{opacity:1;}.src #sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');opacity:0.75;}@media (max-width:850px){#search-tabs .count{display:block;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}.rustdoc{display:block;}main{padding-left:15px;padding-top:0px;}.main-heading{flex-direction:column;}.out-of-band{text-align:left;margin-left:initial;padding:initial;}.out-of-band .since::before{content:"Since ";}.sidebar .logo-container,.sidebar .location,.sidebar-resizer{display:none;}.sidebar{position:fixed;top:45px;left:-1000px;z-index:11;height:calc(100vh - 45px);width:200px;}.src main,.rustdoc.src .sidebar{top:0;padding:0;height:100vh;border:0;}.src .search-form{margin-left:40px;}.hide-sidebar .search-form{margin-left:32px;}.hide-sidebar .src .search-form{margin-left:0;}.sidebar.shown,.src-sidebar-expanded .src .sidebar,.rustdoc:not(.src) .sidebar:focus-within{left:0;}.mobile-topbar h2{padding-bottom:0;margin:auto 0.5em auto auto;overflow:hidden;font-size:24px;white-space:nowrap;text-overflow:ellipsis;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin:5px 0 5px 20px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.hide-sidebar .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;border:none;line-height:0;}.hide-sidebar .sidebar-menu-toggle{display:none;}.sidebar-elems{margin-top:1em;}.anchor{display:none !important;}#main-content>details.toggle>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}#copy-path,#help-button{display:none;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}.sidebar-menu-toggle:before{filter:var(--mobile-sidebar-menu-filter);}.sidebar-menu-toggle:hover{background:var(--main-background-color);}.item-table,.item-row,.item-table>li,.item-table>li>div,.search-results>a,.search-results>a>div{display:block;}.search-results>a{padding:5px 0px;}.search-results>a>div.desc,.item-table>li>div.desc{padding-left:2em;}.search-results .result-name{display:block;}.search-results .result-name .typename{width:initial;margin-right:0;}.search-results .result-name .typename,.search-results .result-name .path{display:inline;}.src-sidebar-expanded .src .sidebar{position:fixed;max-width:100vw;width:100vw;}.src .src-sidebar-title{padding-top:0;}details.toggle:not(.top-doc)>summary{margin-left:10px;}.impl-items>details.toggle>summary:not(.hideme)::before,#main-content>details.toggle:not(.top-doc)>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}.impl-items>.item-info{margin-left:34px;}.src nav.sub{margin:0;padding:var(--nav-sub-mobile-padding);}}@media (min-width:701px){.scraped-example-title{position:absolute;z-index:10;background:var(--main-background-color);bottom:8px;right:5px;padding:2px 4px;box-shadow:0 0 4px var(--main-background-color);}}@media print{nav.sidebar,nav.sub,.out-of-band,a.src,#copy-path,details.toggle[open] >summary::before,details.toggle>summary::before,details.toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}nav.sub{flex-direction:column;}.search-form{align-self:stretch;}}.variant,.implementors-toggle>summary,.impl,#implementors-list>.docblock,.impl-items>section,.impl-items>.toggle>summary,.methods>section,.methods>.toggle>summary{margin-bottom:0.75em;}.variants>.docblock,.implementors-toggle>.docblock,.impl-items>.toggle[open]:not(:last-child),.methods>.toggle[open]:not(:last-child),.implementors-toggle[open]:not(:last-child){margin-bottom:2em;}#trait-implementations-list .impl-items>.toggle:not(:last-child),#synthetic-implementations-list .impl-items>.toggle:not(:last-child),#blanket-implementations-list .impl-items>.toggle:not(:last-child){margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;border:1px solid var(--scrape-example-help-border-color);border-radius:50px;color:var(--scrape-example-help-color);}.scraped-example-list .scrape-help:hover{border-color:var(--scrape-example-help-hover-border-color);color:var(--scrape-example-help-hover-color);}.scraped-example{position:relative;}.scraped-example .code-wrapper{position:relative;display:flex;flex-direction:row;flex-wrap:wrap;width:100%;}.scraped-example:not(.expanded) .code-wrapper{max-height:calc(1.5em * 5 + 10px);}.scraped-example:not(.expanded) .code-wrapper pre{overflow-y:hidden;padding-bottom:0;max-height:calc(1.5em * 5 + 10px);}.more-scraped-examples .scraped-example:not(.expanded) .code-wrapper,.more-scraped-examples .scraped-example:not(.expanded) .code-wrapper pre{max-height:calc(1.5em * 10 + 10px);}.scraped-example .code-wrapper .next,.scraped-example .code-wrapper .prev,.scraped-example .code-wrapper .expand{color:var(--main-color);position:absolute;top:0.25em;z-index:1;padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.scraped-example .code-wrapper .prev{right:2.25em;}.scraped-example .code-wrapper .next{right:1.25em;}.scraped-example .code-wrapper .expand{right:0.25em;}.scraped-example:not(.expanded) .code-wrapper::before,.scraped-example:not(.expanded) .code-wrapper::after{content:" ";width:100%;height:5px;position:absolute;z-index:1;}.scraped-example:not(.expanded) .code-wrapper::before{top:0;background:linear-gradient(to bottom,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded) .code-wrapper::after{bottom:0;background:linear-gradient(to top,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example .code-wrapper .example-wrap{width:100%;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded) .code-wrapper .example-wrap{overflow-x:hidden;}.scraped-example .example-wrap .rust span.highlight{background:var(--scrape-example-code-line-highlight);}.scraped-example .example-wrap .rust span.highlight.focus{background:var(--scrape-example-code-line-highlight-focus);}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;cursor:pointer;}.more-scraped-examples{margin-left:25px;position:relative;}.toggle-line{position:absolute;top:5px;bottom:0;right:calc(100% + 10px);padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;background:var(--scrape-example-toggle-line-background);}.toggle-line:hover .toggle-line-inner{background:var(--scrape-example-toggle-line-hover-background);}.more-scraped-examples .scraped-example,.example-links{margin-top:20px;}.more-scraped-examples .scraped-example:first-child{margin-top:5px;}.example-links ul{margin-bottom:0;}:root[data-theme="light"]{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--test-arrow-color:#f5f5f5;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#f5f5f5;--test-arrow-hover-background-color:rgb(78,139,202);--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="dark"]{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--test-arrow-color:#dedede;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#dedede;--test-arrow-hover-background-color:#4e8bca;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="ayu"]{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--settings-input-border-color:#999;--settings-button-color:#fff;--settings-button-border-focus:#e0e0e0;--sidebar-background-color:#14191f;--sidebar-background-color-hover:rgba(70,70,70,0.33);--code-block-background-color:#191f26;--scrollbar-track-background-color:transparent;--scrollbar-thumb-background-color:#5c6773;--scrollbar-color:#5c6773 #24292f;--headings-border-bottom-color:#5c6773;--border-color:#5c6773;--button-background-color:#141920;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#5c6773;--copy-path-button-color:#fff;--copy-path-img-filter:invert(70%);--copy-path-img-hover-filter:invert(100%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ffa0a5;--trait-link-color:#39afd7;--assoc-item-link-color:#39afd7;--function-link-color:#fdd687;--macro-link-color:#a37acc;--keyword-link-color:#39afd7;--mod-link-color:#39afd7;--link-color:#39afd7;--sidebar-link-color:#53b1db;--sidebar-current-link-background-color:transparent;--search-result-link-focus-background-color:#3c3c3c;--search-result-border-color:#aaa3;--search-color:#fff;--search-error-code-background-color:#4f4c4c;--search-results-alias-color:#c5c5c5;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:none;--search-tab-button-not-selected-background:transparent !important;--search-tab-button-selected-border-top-color:none;--search-tab-button-selected-background:#141920 !important;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ff7733;--code-highlight-kw-2-color:#ff7733;--code-highlight-lifetime-color:#ff7733;--code-highlight-prelude-color:#69f2df;--code-highlight-prelude-val-color:#ff7733;--code-highlight-number-color:#b8cc52;--code-highlight-string-color:#b8cc52;--code-highlight-literal-color:#ff7733;--code-highlight-attribute-color:#e6e1cf;--code-highlight-self-color:#36a3d9;--code-highlight-macro-color:#a37acc;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#788797;--code-highlight-doc-comment-color:#a1ac88;--src-line-numbers-span-color:#5c6773;--src-line-number-highlighted-background-color:rgba(255,236,164,0.06);--test-arrow-color:#788797;--test-arrow-background-color:rgba(57,175,215,0.09);--test-arrow-hover-color:#c5c5c5;--test-arrow-hover-background-color:rgba(57,175,215,0.368);--target-background-color:rgba(255,236,164,0.06);--target-border-color:rgba(255,180,76,0.85);--kbd-color:#c5c5c5;--kbd-background:#314559;--kbd-box-shadow-color:#5c6773;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(41%) sepia(12%) saturate(487%) hue-rotate(171deg) brightness(94%) contrast(94%);--crate-search-div-hover-filter:invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%);--crate-search-hover-border:#e0e0e0;--src-sidebar-background-selected:#14191f;--src-sidebar-background-hover:#14191f;--table-alt-row-background-color:#191f26;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(15,20,25,1);--scrape-example-code-wrapper-background-end:rgba(15,20,25,0);--sidebar-resizer-hover:hsl(34,50%,33%);--sidebar-resizer-active:hsl(34,100%,66%);}:root[data-theme="ayu"] h1,:root[data-theme="ayu"] h2,:root[data-theme="ayu"] h3,:root[data-theme="ayu"] h4,:where(:root[data-theme="ayu"]) h1 a,:root[data-theme="ayu"] .sidebar h2 a,:root[data-theme="ayu"] .sidebar h3 a{color:#fff;}:root[data-theme="ayu"] .docblock code{color:#ffb454;}:root[data-theme="ayu"] .docblock a>code{color:#39AFD7 !important;}:root[data-theme="ayu"] .code-header,:root[data-theme="ayu"] .docblock pre>code,:root[data-theme="ayu"] pre,:root[data-theme="ayu"] pre>code,:root[data-theme="ayu"] .item-info code,:root[data-theme="ayu"] .rustdoc.source .example-wrap{color:#e6e1cf;}:root[data-theme="ayu"] .sidebar .current,:root[data-theme="ayu"] .sidebar .current a,:root[data-theme="ayu"] .sidebar a:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:hover,:root[data-theme="ayu"] details.dir-entry summary:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:focus,:root[data-theme="ayu"] details.dir-entry summary:focus,:root[data-theme="ayu"] #src-sidebar div.files>a.selected{color:#ffb44c;}:root[data-theme="ayu"] .sidebar-elems .location{color:#ff7733;}:root[data-theme="ayu"] .src-line-numbers .line-highlighted{color:#708090;padding-right:7px;border-right:1px solid #ffb44c;}:root[data-theme="ayu"] .search-results a:hover,:root[data-theme="ayu"] .search-results a:focus{color:#fff !important;background-color:#3c3c3c;}:root[data-theme="ayu"] .search-results a{color:#0096cf;}:root[data-theme="ayu"] .search-results a div.desc{color:#c5c5c5;}:root[data-theme="ayu"] .result-name .primitive>i,:root[data-theme="ayu"] .result-name .keyword>i{color:#788797;}:root[data-theme="ayu"] #search-tabs>button.selected{border-bottom:1px solid #ffb44c !important;border-top:none;}:root[data-theme="ayu"] #search-tabs>button:not(.selected){border:none;background-color:transparent !important;}:root[data-theme="ayu"] #search-tabs>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}:root[data-theme="ayu"] #settings-menu>a img,:root[data-theme="ayu"] #sidebar-button>a:before{filter:invert(100);} \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/scrape-examples-ef1e698c1d417c0c.js b/Documentation/RustDoc/static.files/scrape-examples-ef1e698c1d417c0c.js new file mode 100644 index 00000000..ba830e37 --- /dev/null +++ b/Documentation/RustDoc/static.files/scrape-examples-ef1e698c1d417c0c.js @@ -0,0 +1 @@ +"use strict";(function(){const DEFAULT_MAX_LINES=5;const HIDDEN_MAX_LINES=10;function scrollToLoc(elt,loc,isHidden){const lines=elt.querySelector(".src-line-numbers");let scrollOffset;const maxLines=isHidden?HIDDEN_MAX_LINES:DEFAULT_MAX_LINES;if(loc[1]-loc[0]>maxLines){const line=Math.max(0,loc[0]-1);scrollOffset=lines.children[line].offsetTop}else{const wrapper=elt.querySelector(".code-wrapper");const halfHeight=wrapper.offsetHeight/2;const offsetTop=lines.children[loc[0]].offsetTop;const lastLine=lines.children[loc[1]];const offsetBot=lastLine.offsetTop+lastLine.offsetHeight;const offsetMid=(offsetTop+offsetBot)/2;scrollOffset=offsetMid-halfHeight}lines.scrollTo(0,scrollOffset);elt.querySelector(".rust").scrollTo(0,scrollOffset)}function updateScrapedExample(example,isHidden){const locs=JSON.parse(example.attributes.getNamedItem("data-locs").textContent);let locIndex=0;const highlights=Array.prototype.slice.call(example.querySelectorAll(".highlight"));const link=example.querySelector(".scraped-example-title a");if(locs.length>1){const onChangeLoc=changeIndex=>{removeClass(highlights[locIndex],"focus");changeIndex();scrollToLoc(example,locs[locIndex][0],isHidden);addClass(highlights[locIndex],"focus");const url=locs[locIndex][1];const title=locs[locIndex][2];link.href=url;link.innerHTML=title};example.querySelector(".prev").addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex-1+locs.length)%locs.length})});example.querySelector(".next").addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex+1)%locs.length})})}const expandButton=example.querySelector(".expand");if(expandButton){expandButton.addEventListener("click",()=>{if(hasClass(example,"expanded")){removeClass(example,"expanded");scrollToLoc(example,locs[0][0],isHidden)}else{addClass(example,"expanded")}})}scrollToLoc(example,locs[0][0],isHidden)}const firstExamples=document.querySelectorAll(".scraped-example-list > .scraped-example");onEachLazy(firstExamples,el=>updateScrapedExample(el,false));onEachLazy(document.querySelectorAll(".more-examples-toggle"),toggle=>{onEachLazy(toggle.querySelectorAll(".toggle-line, .hide-more"),button=>{button.addEventListener("click",()=>{toggle.open=false})});const moreExamples=toggle.querySelectorAll(".scraped-example");toggle.querySelector("summary").addEventListener("click",()=>{setTimeout(()=>{onEachLazy(moreExamples,el=>updateScrapedExample(el,true))})},{once:true})})})() \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/search-42d8da7a6b9792c2.js b/Documentation/RustDoc/static.files/search-42d8da7a6b9792c2.js new file mode 100644 index 00000000..1d178d53 --- /dev/null +++ b/Documentation/RustDoc/static.files/search-42d8da7a6b9792c2.js @@ -0,0 +1,5 @@ +"use strict";if(!Array.prototype.toSpliced){Array.prototype.toSpliced=function(){const me=this.slice();Array.prototype.splice.apply(me,arguments);return me}}(function(){const itemTypes=["keyword","primitive","mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","associatedtype","constant","associatedconstant","union","foreigntype","existential","attr","derive","traitalias","generic",];const longItemTypes=["keyword","primitive type","module","extern crate","re-export","struct","enum","function","type alias","static","trait","","trait method","method","struct field","enum variant","macro","assoc type","constant","assoc const","union","foreign type","existential type","attribute macro","derive macro","trait alias",];const TY_GENERIC=itemTypes.indexOf("generic");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";const UNBOXING_LIMIT=5;function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("search-tabs").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}iter+=1});const isTypeSearch=(nb>0||iter===1);iter=0;onEachLazy(document.getElementById("results").childNodes,elem=>{if(nb===iter){addClass(elem,"active");foundCurrentResultSet=true}else{removeClass(elem,"active")}iter+=1});if(foundCurrentTab&&foundCurrentResultSet){searchState.currentTab=nb;const correctionsElem=document.getElementsByClassName("search-corrections");if(isTypeSearch){removeClass(correctionsElem[0],"hidden")}else{addClass(correctionsElem[0],"hidden")}}else if(nb!==0){printTab(0)}}const editDistanceState={current:[],prev:[],prevPrev:[],calculate:function calculate(a,b,limit){if(a.lengthlimit){return limit+1}while(b.length>0&&b[0]===a[0]){a=a.substring(1);b=b.substring(1)}while(b.length>0&&b[b.length-1]===a[a.length-1]){a=a.substring(0,a.length-1);b=b.substring(0,b.length-1)}if(b.length===0){return minDist}const aLength=a.length;const bLength=b.length;for(let i=0;i<=bLength;++i){this.current[i]=0;this.prev[i]=i;this.prevPrev[i]=Number.MAX_VALUE}for(let i=1;i<=aLength;++i){this.current[0]=i;const aIdx=i-1;for(let j=1;j<=bLength;++j){const bIdx=j-1;const substitutionCost=a[aIdx]===b[bIdx]?0:1;this.current[j]=Math.min(this.prev[j]+1,this.current[j-1]+1,this.prev[j-1]+substitutionCost);if((i>1)&&(j>1)&&(a[aIdx]===b[bIdx-1])&&(a[aIdx-1]===b[bIdx])){this.current[j]=Math.min(this.current[j],this.prevPrev[j-2]+1)}}const prevPrevTmp=this.prevPrev;this.prevPrev=this.prev;this.prev=this.current;this.current=prevPrevTmp}const distance=this.prev[bLength];return distance<=limit?distance:(limit+1)},};function editDistance(a,b,limit){return editDistanceState.calculate(a,b,limit)}function initSearch(rawSearchIndex){const MAX_RESULTS=200;const NO_TYPE_FILTER=-1;let searchIndex;let functionTypeFingerprint;let currentResults;const typeNameIdMap=new Map();const ALIASES=new Map();const typeNameIdOfArray=buildTypeMapIndex("array");const typeNameIdOfSlice=buildTypeMapIndex("slice");const typeNameIdOfArrayOrSlice=buildTypeMapIndex("[]");const typeNameIdOfTuple=buildTypeMapIndex("tuple");const typeNameIdOfUnit=buildTypeMapIndex("unit");const typeNameIdOfTupleOrUnit=buildTypeMapIndex("()");const typeNameIdOfFn=buildTypeMapIndex("fn");const typeNameIdOfFnMut=buildTypeMapIndex("fnmut");const typeNameIdOfFnOnce=buildTypeMapIndex("fnonce");const typeNameIdOfHof=buildTypeMapIndex("->");function buildTypeMapIndex(name,isAssocType){if(name===""||name===null){return null}if(typeNameIdMap.has(name)){const obj=typeNameIdMap.get(name);obj.assocOnly=isAssocType&&obj.assocOnly;return obj.id}else{const id=typeNameIdMap.size;typeNameIdMap.set(name,{id,assocOnly:isAssocType});return id}}function isSpecialStartCharacter(c){return"<\"".indexOf(c)!==-1}function isEndCharacter(c){return"=,>-])".indexOf(c)!==-1}function itemTypeFromName(typename){const index=itemTypes.findIndex(i=>i===typename);if(index<0){throw["Unknown type filter ",typename]}return index}function getStringElem(query,parserState,isInGenerics){if(isInGenerics){throw["Unexpected ","\""," in generics"]}else if(query.literalSearch){throw["Cannot have more than one literal search element"]}else if(parserState.totalElems-parserState.genericsElems>0){throw["Cannot use literal search when there is more than one element"]}parserState.pos+=1;const start=parserState.pos;const end=getIdentEndPosition(parserState);if(parserState.pos>=parserState.length){throw["Unclosed ","\""]}else if(parserState.userQuery[end]!=="\""){throw["Unexpected ",parserState.userQuery[end]," in a string element"]}else if(start===end){throw["Cannot have empty string element"]}parserState.pos+=1;query.literalSearch=true}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function isIdentCharacter(c){return(c==="_"||(c>="0"&&c<="9")||(c>="a"&&c<="z")||(c>="A"&&c<="Z"))}function isSeparatorCharacter(c){return c===","||c==="="}function isPathSeparator(c){return c===":"||c===" "}function prevIs(parserState,lookingFor){let pos=parserState.pos;while(pos>0){const c=parserState.userQuery[pos-1];if(c===lookingFor){return true}else if(c!==" "){break}pos-=1}return false}function isLastElemGeneric(elems,parserState){return(elems.length>0&&elems[elems.length-1].generics.length>0)||prevIs(parserState,">")}function skipWhitespace(parserState){while(parserState.pos0){throw["Cannot have more than one element if you use quotes"]}const typeFilter=parserState.typeFilter;parserState.typeFilter=null;if(name==="!"){if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive never type ","!"," and ",typeFilter," both specified",]}if(generics.length!==0){throw["Never type ","!"," does not accept generic parameters",]}const bindingName=parserState.isInBinding;parserState.isInBinding=null;return makePrimitiveElement("never",{bindingName})}const quadcolon=/::\s*::/.exec(path);if(path.startsWith("::")){throw["Paths cannot start with ","::"]}else if(path.endsWith("::")){throw["Paths cannot end with ","::"]}else if(quadcolon!==null){throw["Unexpected ",quadcolon[0]]}const pathSegments=path.split(/(?:::\s*)|(?:\s+(?:::\s*)?)/);if(pathSegments.length===0||(pathSegments.length===1&&pathSegments[0]==="")){if(generics.length>0||prevIs(parserState,">")){throw["Found generics without a path"]}else{throw["Unexpected ",parserState.userQuery[parserState.pos]]}}for(const[i,pathSegment]of pathSegments.entries()){if(pathSegment==="!"){if(i!==0){throw["Never type ","!"," is not associated item"]}pathSegments[i]="never"}}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}const bindingName=parserState.isInBinding;parserState.isInBinding=null;const bindings=new Map();const pathLast=pathSegments[pathSegments.length-1];return{name:name.trim(),id:null,fullPath:pathSegments,pathWithoutLast:pathSegments.slice(0,pathSegments.length-1),pathLast,normalizedPathLast:pathLast.replace(/_/g,""),generics:generics.filter(gen=>{if(gen.bindingName!==null){if(gen.name!==null){gen.bindingName.generics.unshift(gen)}bindings.set(gen.bindingName.name,gen.bindingName.generics);return false}return true}),bindings,typeFilter,bindingName,}}function getIdentEndPosition(parserState){const start=parserState.pos;let end=parserState.pos;let foundExclamation=-1;while(parserState.pos0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]]}else{throw["Unexpected ",c]}}parserState.pos+=1;end=parserState.pos}if(foundExclamation!==-1&&foundExclamation!==start&&isIdentCharacter(parserState.userQuery[foundExclamation-1])){if(parserState.typeFilter===null){parserState.typeFilter="macro"}else if(parserState.typeFilter!=="macro"){throw["Invalid search type: macro ","!"," and ",parserState.typeFilter," both specified",]}end=foundExclamation}return end}function getFilteredNextElem(query,parserState,elems,isInGenerics){const start=parserState.pos;if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){throw["Expected type filter before ",":"]}getNextElem(query,parserState,elems,isInGenerics);if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}if(elems.length===0){throw["Expected type filter before ",":"]}else if(query.literalSearch){throw["Cannot use quotes on type filter"]}const typeFilterElem=elems.pop();checkExtraTypeFilterCharacters(start,parserState);parserState.typeFilter=typeFilterElem.name;parserState.pos+=1;parserState.totalElems-=1;query.literalSearch=false;getNextElem(query,parserState,elems,isInGenerics)}}function getNextElem(query,parserState,elems,isInGenerics){const generics=[];skipWhitespace(parserState);let start=parserState.pos;let end;if("[(".indexOf(parserState.userQuery[parserState.pos])!==-1){let endChar=")";let name="()";let friendlyName="tuple";if(parserState.userQuery[parserState.pos]==="["){endChar="]";name="[]";friendlyName="slice"}parserState.pos+=1;const{foundSeparator}=getItemsBefore(query,parserState,generics,endChar);const typeFilter=parserState.typeFilter;const bindingName=parserState.isInBinding;parserState.typeFilter=null;parserState.isInBinding=null;for(const gen of generics){if(gen.bindingName!==null){throw["Type parameter ","=",` cannot be within ${friendlyName} `,name]}}if(name==="()"&&!foundSeparator&&generics.length===1&&typeFilter===null){elems.push(generics[0])}else if(name==="()"&&generics.length===1&&generics[0].name==="->"){generics[0].typeFilter=typeFilter;elems.push(generics[0])}else{if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive ",name," and ",typeFilter," both specified",]}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}elems.push(makePrimitiveElement(name,{bindingName,generics}))}}else{const isStringElem=parserState.userQuery[start]==="\"";if(isStringElem){start+=1;getStringElem(query,parserState,isInGenerics);end=parserState.pos-1}else{end=getIdentEndPosition(parserState)}if(parserState.pos=end){throw["Found generics without a path"]}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}else if(parserState.pos=end){throw["Found generics without a path"]}if(parserState.isInBinding){throw["Unexpected ","("," after ","="]}parserState.pos+=1;const typeFilter=parserState.typeFilter;parserState.typeFilter=null;getItemsBefore(query,parserState,generics,")");skipWhitespace(parserState);if(isReturnArrow(parserState)){parserState.pos+=2;skipWhitespace(parserState);getFilteredNextElem(query,parserState,generics,isInGenerics);generics[generics.length-1].bindingName=makePrimitiveElement("output")}else{generics.push(makePrimitiveElement(null,{bindingName:makePrimitiveElement("output"),typeFilter:null,}))}parserState.typeFilter=typeFilter}if(isStringElem){skipWhitespace(parserState)}if(start>=end&&generics.length===0){return}if(parserState.userQuery[parserState.pos]==="="){if(parserState.isInBinding){throw["Cannot write ","="," twice in a binding"]}if(!isInGenerics){throw["Type parameter ","="," must be within generics list"]}const name=parserState.userQuery.slice(start,end).trim();if(name==="!"){throw["Type parameter ","="," key cannot be ","!"," never type"]}if(name.includes("!")){throw["Type parameter ","="," key cannot be ","!"," macro"]}if(name.includes("::")){throw["Type parameter ","="," key cannot contain ","::"," path"]}if(name.includes(":")){throw["Type parameter ","="," key cannot contain ",":"," type"]}parserState.isInBinding={name,generics}}else{elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics))}}}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;let foundSeparator=false;const oldTypeFilter=parserState.typeFilter;parserState.typeFilter=null;const oldIsInBinding=parserState.isInBinding;parserState.isInBinding=null;let hofParameters=null;let extra="";if(endChar===">"){extra="<"}else if(endChar==="]"){extra="["}else if(endChar===")"){extra="("}else if(endChar===""){extra="->"}else{extra=endChar}while(parserState.pos"," after ","="]}hofParameters=[...elems];elems.length=0;parserState.pos+=2;foundStopChar=true;foundSeparator=false;continue}else if(c===" "){parserState.pos+=1;continue}else if(isSeparatorCharacter(c)){parserState.pos+=1;foundStopChar=true;foundSeparator=true;continue}else if(c===":"&&isPathStart(parserState)){throw["Unexpected ","::",": paths cannot start with ","::"]}else if(isEndCharacter(c)){throw["Unexpected ",c," after ",extra]}if(!foundStopChar){let extra=[];if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(endChar!==""){throw["Expected ",",",", ","=",", or ",endChar,...extra,", found ",c,]}throw["Expected ",","," or ","=",...extra,", found ",c,]}const posBefore=parserState.pos;getFilteredNextElem(query,parserState,elems,endChar!=="");if(endChar!==""&&parserState.pos>=parserState.length){throw["Unclosed ",extra]}if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}if(parserState.pos>=parserState.length&&endChar!==""){throw["Unclosed ",extra]}parserState.pos+=1;if(hofParameters){foundSeparator=false;if([...elems,...hofParameters].some(x=>x.bindingName)||parserState.isInBinding){throw["Unexpected ","="," within ","->"]}const hofElem=makePrimitiveElement("->",{generics:hofParameters,bindings:new Map([["output",[...elems]]]),typeFilter:null,});elems.length=0;elems[0]=hofElem}parserState.typeFilter=oldTypeFilter;parserState.isInBinding=oldIsInBinding;return{foundSeparator}}function checkExtraTypeFilterCharacters(start,parserState){const query=parserState.userQuery.slice(start,parserState.pos).trim();for(const c in query){if(!isIdentCharacter(query[c])){throw["Unexpected ",query[c]," in type filter (before ",":",")",]}}}function parseInput(query,parserState){let foundStopChar=true;while(parserState.pos"){if(isReturnArrow(parserState)){break}throw["Unexpected ",c," (did you mean ","->","?)"]}else if(parserState.pos>0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]]}throw["Unexpected ",c]}else if(c===" "){skipWhitespace(parserState);continue}if(!foundStopChar){let extra="";if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(parserState.typeFilter!==null){throw["Expected ",","," or ","->",...extra,", found ",c,]}throw["Expected ",",",", ",":"," or ","->",...extra,", found ",c,]}const before=query.elems.length;getFilteredNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}while(parserState.pos"]}break}else{parserState.pos+=1}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),elems:[],returned:[],foundElems:0,totalElems:0,literalSearch:false,error:null,correction:null,proposeCorrectionFrom:null,proposeCorrectionTo:null,typeFingerprint:new Uint32Array(4),}}function buildUrl(search,filterCrates){let extra="?search="+encodeURIComponent(search);if(filterCrates!==null){extra+="&filter-crate="+encodeURIComponent(filterCrates)}return getNakedUrl()+extra+window.location.hash}function getFilterCrates(){const elem=document.getElementById("crate-search");if(elem&&elem.value!=="all crates"&&rawSearchIndex.has(elem.value)){return elem.value}return null}function parseQuery(userQuery){function convertTypeFilterOnElem(elem){if(elem.typeFilter!==null){let typeFilter=elem.typeFilter;if(typeFilter==="const"){typeFilter="constant"}elem.typeFilter=itemTypeFromName(typeFilter)}else{elem.typeFilter=NO_TYPE_FILTER}for(const elem2 of elem.generics){convertTypeFilterOnElem(elem2)}for(const constraints of elem.bindings.values()){for(const constraint of constraints){convertTypeFilterOnElem(constraint)}}}userQuery=userQuery.trim().replace(/\r|\n|\t/g," ");const parserState={length:userQuery.length,pos:0,totalElems:0,genericsElems:0,typeFilter:null,isInBinding:null,userQuery:userQuery.toLowerCase(),};let query=newParsedQuery(userQuery);try{parseInput(query,parserState);for(const elem of query.elems){convertTypeFilterOnElem(elem)}for(const elem of query.returned){convertTypeFilterOnElem(elem)}}catch(err){query=newParsedQuery(userQuery);query.error=err;return query}if(!query.literalSearch){query.literalSearch=parserState.totalElems>1}query.foundElems=query.elems.length+query.returned.length;query.totalElems=parserState.totalElems;return query}function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}function execQuery(parsedQuery,filterCrates,currentCrate){const results_others=new Map(),results_in_args=new Map(),results_returned=new Map();function transformResults(results){const duplicates=new Set();const out=[];for(const result of results){if(result.id!==-1){const obj=searchIndex[result.id];obj.dist=result.dist;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=obj.displayPath+obj.name;obj.fullPath+="|"+obj.ty;if(duplicates.has(obj.fullPath)){continue}duplicates.add(obj.fullPath);obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out}function sortResults(results,isType,preferredCrate){const userQuery=parsedQuery.userQuery;const result_list=[];for(const result of results.values()){result.item=searchIndex[result.id];result.word=searchIndex[result.id].word;result_list.push(result)}result_list.sort((aaa,bbb)=>{let a,b;a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.path_dist;b=bbb.path_dist;if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}a=(aaa.dist);b=(bbb.dist);if(a!==b){return a-b}a=aaa.item.deprecated;b=bbb.item.deprecated;if(a!==b){return a-b}a=(aaa.item.crate!==preferredCrate);b=(bbb.item.crate!==preferredCrate);if(a!==b){return a-b}a=aaa.word.length;b=bbb.word.length;if(a!==b){return a-b}a=aaa.word;b=bbb.word;if(a!==b){return(a>b?+1:-1)}a=(aaa.item.desc==="");b=(bbb.item.desc==="");if(a!==b){return a-b}a=aaa.item.ty;b=bbb.item.ty;if(a!==b){return a-b}a=aaa.item.path;b=bbb.item.path;if(a!==b){return(a>b?+1:-1)}return 0});return transformResults(result_list)}function unifyFunctionTypes(fnTypesIn,queryElems,whereClause,mgensIn,solutionCb,unboxingDepth){if(unboxingDepth>=UNBOXING_LIMIT){return false}const mgens=mgensIn===null?null:new Map(mgensIn);if(queryElems.length===0){return!solutionCb||solutionCb(mgens)}if(!fnTypesIn||fnTypesIn.length===0){return false}const ql=queryElems.length;const fl=fnTypesIn.length;if(ql===1&&queryElems[0].generics.length===0&&queryElems[0].bindings.size===0){const queryElem=queryElems[0];for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}if(fnType.id<0&&queryElem.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==queryElem.id){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,queryElem.id);if(!solutionCb||solutionCb(mgensScratch)){return true}}else if(!solutionCb||solutionCb(mgens?new Map(mgens):null)){return true}}for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1)){continue}if(fnType.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,0);if(unifyFunctionTypes(whereClause[(-fnType.id)-1],queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1)){return true}}else if(unifyFunctionTypes([...fnType.generics,...Array.from(fnType.bindings.values()).flat()],queryElems,whereClause,mgens?new Map(mgens):null,solutionCb,unboxingDepth+1)){return true}}return false}const fnTypes=fnTypesIn.slice();const flast=fl-1;const qlast=ql-1;const queryElem=queryElems[qlast];let queryElemsTmp=null;for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==queryElem.id){continue}mgensScratch.set(fnType.id,queryElem.id)}else{mgensScratch=mgens}fnTypes[i]=fnTypes[flast];fnTypes.length=flast;if(!queryElemsTmp){queryElemsTmp=queryElems.slice(0,qlast)}const passesUnification=unifyFunctionTypes(fnTypes,queryElemsTmp,whereClause,mgensScratch,mgensScratch=>{if(fnType.generics.length===0&&queryElem.generics.length===0&&fnType.bindings.size===0&&queryElem.bindings.size===0){return!solutionCb||solutionCb(mgensScratch)}const solution=unifyFunctionTypeCheckBindings(fnType,queryElem,whereClause,mgensScratch,unboxingDepth);if(!solution){return false}const simplifiedGenerics=solution.simplifiedGenerics;for(const simplifiedMgens of solution.mgens){const passesUnification=unifyFunctionTypes(simplifiedGenerics,queryElem.generics,whereClause,simplifiedMgens,solutionCb,unboxingDepth);if(passesUnification){return true}}return false},unboxingDepth);if(passesUnification){return true}fnTypes[flast]=fnTypes[i];fnTypes[i]=fnType;fnTypes.length=fl}for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==0){continue}mgensScratch.set(fnType.id,0)}else{mgensScratch=mgens}const generics=fnType.id<0?whereClause[(-fnType.id)-1]:fnType.generics;const bindings=fnType.bindings?Array.from(fnType.bindings.values()).flat():[];const passesUnification=unifyFunctionTypes(fnTypes.toSpliced(i,1,...generics,...bindings),queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1);if(passesUnification){return true}}return false}function unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgensIn){if(!typePassesFilter(queryElem.typeFilter,fnType.ty)){return false}if(fnType.id<0&&queryElem.id<0){if(mgensIn){if(mgensIn.has(fnType.id)&&mgensIn.get(fnType.id)!==queryElem.id){return false}for(const[fid,qid]of mgensIn.entries()){if(fnType.id!==fid&&queryElem.id===qid){return false}if(fnType.id===fid&&queryElem.id!==qid){return false}}}return true}else{if(queryElem.id===typeNameIdOfArrayOrSlice&&(fnType.id===typeNameIdOfSlice||fnType.id===typeNameIdOfArray)){}else if(queryElem.id===typeNameIdOfTupleOrUnit&&(fnType.id===typeNameIdOfTuple||fnType.id===typeNameIdOfUnit)){}else if(queryElem.id===typeNameIdOfHof&&(fnType.id===typeNameIdOfFn||fnType.id===typeNameIdOfFnMut||fnType.id===typeNameIdOfFnOnce)){}else if(fnType.id!==queryElem.id||queryElem.id===null){return false}if((fnType.generics.length+fnType.bindings.size)===0&&queryElem.generics.length!==0){return false}if(fnType.bindings.size0){const fnTypePath=fnType.path!==undefined&&fnType.path!==null?fnType.path.split("::"):[];if(queryElemPathLength>fnTypePath.length){return false}let i=0;for(const path of fnTypePath){if(path===queryElem.pathWithoutLast[i]){i+=1;if(i>=queryElemPathLength){break}}}if(i0){let mgensSolutionSet=[mgensIn];for(const[name,constraints]of queryElem.bindings.entries()){if(mgensSolutionSet.length===0){return false}if(!fnType.bindings.has(name)){return false}const fnTypeBindings=fnType.bindings.get(name);mgensSolutionSet=mgensSolutionSet.flatMap(mgens=>{const newSolutions=[];unifyFunctionTypes(fnTypeBindings,constraints,whereClause,mgens,newMgens=>{newSolutions.push(newMgens);return false},unboxingDepth);return newSolutions})}if(mgensSolutionSet.length===0){return false}const binds=Array.from(fnType.bindings.entries()).flatMap(entry=>{const[name,constraints]=entry;if(queryElem.bindings.has(name)){return[]}else{return constraints}});if(simplifiedGenerics.length>0){simplifiedGenerics=[...simplifiedGenerics,...binds]}else{simplifiedGenerics=binds}return{simplifiedGenerics,mgens:mgensSolutionSet}}return{simplifiedGenerics,mgens:[mgensIn]}}function unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth){if(unboxingDepth>=UNBOXING_LIMIT){return false}if(fnType.id<0&&queryElem.id>=0){if(!whereClause){return false}if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){return false}const mgensTmp=new Map(mgens);mgensTmp.set(fnType.id,null);return checkIfInList(whereClause[(-fnType.id)-1],queryElem,whereClause,mgensTmp,unboxingDepth)}else if(fnType.generics.length>0||fnType.bindings.size>0){const simplifiedGenerics=[...fnType.generics,...Array.from(fnType.bindings.values()).flat(),];return checkIfInList(simplifiedGenerics,queryElem,whereClause,mgens,unboxingDepth)}return false}function checkIfInList(list,elem,whereClause,mgens,unboxingDepth){for(const entry of list){if(checkType(entry,elem,whereClause,mgens,unboxingDepth)){return true}}return false}function checkType(row,elem,whereClause,mgens,unboxingDepth){if(unboxingDepth>=UNBOXING_LIMIT){return false}if(row.bindings.size===0&&elem.bindings.size===0){if(elem.id<0&&mgens===null){return row.id<0||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth+1)}if(row.id>0&&elem.id>0&&elem.pathWithoutLast.length===0&&typePassesFilter(elem.typeFilter,row.ty)&&elem.generics.length===0&&elem.id!==typeNameIdOfArrayOrSlice&&elem.id!==typeNameIdOfTupleOrUnit&&elem.id!==typeNameIdOfHof){return row.id===elem.id||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth)}}return unifyFunctionTypes([row],[elem],whereClause,mgens,null,unboxingDepth)}function checkPath(contains,ty){if(contains.length===0){return 0}const maxPathEditDistance=Math.floor(contains.reduce((acc,next)=>acc+next.length,0)/3);let ret_dist=maxPathEditDistance+1;const path=ty.path.split("::");if(ty.parent&&ty.parent.name){path.push(ty.parent.name.toLowerCase())}const length=path.length;const clength=contains.length;pathiter:for(let i=length-clength;i>=0;i-=1){let dist_total=0;for(let x=0;xmaxPathEditDistance){continue pathiter}dist_total+=dist}}ret_dist=Math.min(ret_dist,Math.round(dist_total/clength))}return ret_dist>maxPathEditDistance?null:ret_dist}function typePassesFilter(filter,type){if(filter<=NO_TYPE_FILTER||filter===type)return true;const name=itemTypes[type];switch(itemTypes[filter]){case"constant":return name==="associatedconstant";case"fn":return name==="method"||name==="tymethod";case"type":return name==="primitive"||name==="associatedtype";case"trait":return name==="traitalias"}return false}function createAliasFromItem(item){return{crate:item.crate,name:item.name,path:item.path,desc:item.desc,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,deprecated:item.deprecated,implDisambiguator:item.implDisambiguator,}}function handleAliases(ret,query,filterCrates,currentCrate){const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(ALIASES.has(filterCrates)&&ALIASES.get(filterCrates).has(lowerQuery)){const query_aliases=ALIASES.get(filterCrates).get(lowerQuery);for(const alias of query_aliases){aliases.push(createAliasFromItem(searchIndex[alias]))}}}else{for(const[crate,crateAliasesIndex]of ALIASES){if(crateAliasesIndex.has(lowerQuery)){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=crateAliasesIndex.get(lowerQuery);for(const alias of query_aliases){pushTo.push(createAliasFromItem(searchIndex[alias]))}}}}const sortFunc=(aaa,bbb)=>{if(aaa.path{alias.alias=query;const res=buildHrefAndPath(alias);alias.displayPath=pathSplitter(res[0]);alias.fullPath=alias.displayPath+alias.name;alias.href=res[1];ret.others.unshift(alias);if(ret.others.length>MAX_RESULTS){ret.others.pop()}};aliases.forEach(pushFunc);crateAliases.forEach(pushFunc)}function addIntoResults(results,fullId,id,index,dist,path_dist,maxEditDistance){if(dist<=maxEditDistance||index!==-1){if(results.has(fullId)){const result=results.get(fullId);if(result.dontValidate||result.dist<=dist){return}}results.set(fullId,{id:id,index:index,dontValidate:parsedQuery.literalSearch,dist:dist,path_dist:path_dist,})}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned,maxEditDistance){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let path_dist=0;const fullId=row.id;const tfpDist=compareTypeFingerprints(fullId,parsedQuery.typeFingerprint);if(tfpDist!==null){const in_args=row.type&&row.type.inputs&&checkIfInList(row.type.inputs,elem,row.type.where_clause,null,0);const returned=row.type&&row.type.output&&checkIfInList(row.type.output,elem,row.type.where_clause,null,0);if(in_args){results_in_args.max_dist=Math.max(results_in_args.max_dist||0,tfpDist);const maxDist=results_in_args.sizenormalizedIndex&&normalizedIndex!==-1)){index=normalizedIndex}if(elem.fullPath.length>1){path_dist=checkPath(elem.pathWithoutLast,row);if(path_dist===null){return}}if(parsedQuery.literalSearch){if(row.word===elem.pathLast){addIntoResults(results_others,fullId,pos,index,0,path_dist)}return}const dist=editDistance(row.normalizedName,elem.normalizedPathLast,maxEditDistance);if(index===-1&&dist>maxEditDistance){return}addIntoResults(results_others,fullId,pos,index,dist,path_dist,maxEditDistance)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)||!row.type){return}const tfpDist=compareTypeFingerprints(row.id,parsedQuery.typeFingerprint);if(tfpDist===null){return}if(results.size>=MAX_RESULTS&&tfpDist>results.max_dist){return}if(!unifyFunctionTypes(row.type.inputs,parsedQuery.elems,row.type.where_clause,null,mgens=>{return unifyFunctionTypes(row.type.output,parsedQuery.returned,row.type.where_clause,mgens,null,0)},0)){return}results.max_dist=Math.max(results.max_dist||0,tfpDist);addIntoResults(results,row.id,pos,0,tfpDist,0,Number.MAX_VALUE)}function innerRunQuery(){const queryLen=parsedQuery.elems.reduce((acc,next)=>acc+next.pathLast.length,0)+parsedQuery.returned.reduce((acc,next)=>acc+next.pathLast.length,0);const maxEditDistance=Math.floor(queryLen/3);const genericSymbols=new Map();function convertNameToId(elem,isAssocType){if(typeNameIdMap.has(elem.normalizedPathLast)&&(isAssocType||!typeNameIdMap.get(elem.normalizedPathLast).assocOnly)){elem.id=typeNameIdMap.get(elem.normalizedPathLast).id}else if(!parsedQuery.literalSearch){let match=null;let matchDist=maxEditDistance+1;let matchName="";for(const[name,{id,assocOnly}]of typeNameIdMap){const dist=editDistance(name,elem.normalizedPathLast,maxEditDistance);if(dist<=matchDist&&dist<=maxEditDistance&&(isAssocType||!assocOnly)){if(dist===matchDist&&matchName>name){continue}match=id;matchDist=dist;matchName=name}}if(match!==null){parsedQuery.correction=matchName}elem.id=match}if((elem.id===null&&parsedQuery.totalElems>1&&elem.typeFilter===-1&&elem.generics.length===0&&elem.bindings.size===0)||elem.typeFilter===TY_GENERIC){if(genericSymbols.has(elem.name)){elem.id=genericSymbols.get(elem.name)}else{elem.id=-(genericSymbols.size+1);genericSymbols.set(elem.name,elem.id)}if(elem.typeFilter===-1&&elem.name.length>=3){const maxPartDistance=Math.floor(elem.name.length/3);let matchDist=maxPartDistance+1;let matchName="";for(const name of typeNameIdMap.keys()){const dist=editDistance(name,elem.name,maxPartDistance);if(dist<=matchDist&&dist<=maxPartDistance){if(dist===matchDist&&matchName>name){continue}matchDist=dist;matchName=name}}if(matchName!==""){parsedQuery.proposeCorrectionFrom=elem.name;parsedQuery.proposeCorrectionTo=matchName}}elem.typeFilter=TY_GENERIC}if(elem.generics.length>0&&elem.typeFilter===TY_GENERIC){parsedQuery.error=["Generic type parameter ",elem.name," does not accept generic parameters",]}for(const elem2 of elem.generics){convertNameToId(elem2)}elem.bindings=new Map(Array.from(elem.bindings.entries()).map(entry=>{const[name,constraints]=entry;if(!typeNameIdMap.has(name)){parsedQuery.error=["Type parameter ",name," does not exist",];return[null,[]]}for(const elem2 of constraints){convertNameToId(elem2)}return[typeNameIdMap.get(name).id,constraints]}))}const fps=new Set();for(const elem of parsedQuery.elems){convertNameToId(elem);buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}for(const elem of parsedQuery.returned){convertNameToId(elem);buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}if(parsedQuery.foundElems===1&&parsedQuery.returned.length===0){if(parsedQuery.elems.length===1){const elem=parsedQuery.elems[0];for(let i=0,nSearchIndex=searchIndex.length;i0){const sortQ=(a,b)=>{const ag=a.generics.length===0&&a.bindings.size===0;const bg=b.generics.length===0&&b.bindings.size===0;if(ag!==bg){return ag-bg}const ai=a.id>0;const bi=b.id>0;return ai-bi};parsedQuery.elems.sort(sortQ);parsedQuery.returned.sort(sortQ);for(let i=0,nSearchIndex=searchIndex.length;i");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}function addTab(array,query,display){const extraClass=display?" active":"";const output=document.createElement("div");if(array.length>0){output.className="search-results "+extraClass;array.forEach(item=>{const name=item.name;const type=itemTypes[item.ty];const longType=longItemTypes[item.ty];const typeName=longType.length!==0?`${longType}`:"?";const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const resultName=document.createElement("div");resultName.className="result-name";resultName.insertAdjacentHTML("beforeend",`${typeName}`);link.appendChild(resultName);let alias=" ";if(item.is_alias){alias=`
    \ +${item.alias} - see \ +
    `}resultName.insertAdjacentHTML("beforeend",`
    ${alias}\ +${item.displayPath}${name}\ +
    `);const description=document.createElement("div");description.className="desc";description.insertAdjacentHTML("beforeend",item.desc);link.appendChild(description);output.appendChild(link)})}else if(query.error===null){output.className="search-failed"+extraClass;output.innerHTML="No results :(
    "+"Try on DuckDuckGo?

    "+"Or try looking in one of these:"}return[output,array.length]}function makeTabHeader(tabNb,text,nbElems){const fmtNbElems=nbElems<10?`\u{2007}(${nbElems})\u{2007}\u{2007}`:nbElems<100?`\u{2007}(${nbElems})\u{2007}`:`\u{2007}(${nbElems})`;if(searchState.currentTab===tabNb){return""}return""}function showResults(results,go_to_first,filterCrates){const search=searchState.outputElement();if(go_to_first||(results.others.length===1&&getSettingValue("go-to-only-result")==="true")){window.onunload=()=>{};searchState.removeQueryParameters();const elem=document.createElement("a");elem.href=results.others[0].href;removeClass(elem,"active");document.body.appendChild(elem);elem.click();return}if(results.query===undefined){results.query=parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const ret_others=addTab(results.others,results.query,true);const ret_in_args=addTab(results.in_args,results.query,false);const ret_returned=addTab(results.returned,results.query,false);let currentTab=searchState.currentTab;if((currentTab===0&&ret_others[1]===0)||(currentTab===1&&ret_in_args[1]===0)||(currentTab===2&&ret_returned[1]===0)){if(ret_others[1]!==0){currentTab=0}else if(ret_in_args[1]!==0){currentTab=1}else if(ret_returned[1]!==0){currentTab=2}}let crates="";if(rawSearchIndex.size>1){crates=" in 
    "}let output=`

    Results${crates}

    `;if(results.query.error!==null){const error=results.query.error;error.forEach((value,index)=>{value=value.split("<").join("<").split(">").join(">");if(index%2!==0){error[index]=`${value.replaceAll(" ", " ")}`}else{error[index]=value}});output+=`

    Query parser error: "${error.join("")}".

    `;output+="
    "+makeTabHeader(0,"In Names",ret_others[1])+"
    ";currentTab=0}else if(results.query.foundElems<=1&&results.query.returned.length===0){output+="
    "+makeTabHeader(0,"In Names",ret_others[1])+makeTabHeader(1,"In Parameters",ret_in_args[1])+makeTabHeader(2,"In Return Types",ret_returned[1])+"
    "}else{const signatureTabTitle=results.query.elems.length===0?"In Function Return Types":results.query.returned.length===0?"In Function Parameters":"In Function Signatures";output+="
    "+makeTabHeader(0,signatureTabTitle,ret_others[1])+"
    ";currentTab=0}if(results.query.correction!==null){const orig=results.query.returned.length>0?results.query.returned[0].name:results.query.elems[0].name;output+="

    "+`Type "${orig}" not found. `+"Showing results for closest type name "+`"${results.query.correction}" instead.

    `}if(results.query.proposeCorrectionFrom!==null){const orig=results.query.proposeCorrectionFrom;const targ=results.query.proposeCorrectionTo;output+="

    "+`Type "${orig}" not found and used as generic parameter. `+`Consider searching for "${targ}" instead.

    `}const resultsElem=document.createElement("div");resultsElem.id="results";resultsElem.appendChild(ret_others[0]);resultsElem.appendChild(ret_in_args[0]);resultsElem.appendChild(ret_returned[0]);search.innerHTML=output;const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("search-tabs").childNodes;searchState.focusedByTab=[];let i=0;for(const elem of elems){const j=i;elem.onclick=()=>printTab(j);searchState.focusedByTab.push(null);i+=1}printTab(currentTab)}function updateSearchHistory(url){if(!browserSupportsHistoryApi()){return}const params=searchState.getQueryStringParams();if(!history.state&&!params.search){history.pushState(null,"",url)}else{history.replaceState(null,"",url)}}function search(forced){const query=parseQuery(searchState.input.value.trim());let filterCrates=getFilterCrates();if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}searchState.setLoadingSearch();const params=searchState.getQueryStringParams();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="Results for "+query.original+" - Rust";updateSearchHistory(buildUrl(query.original,filterCrates));showResults(execQuery(query,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function buildItemSearchTypeAll(types,lowercasePaths){return types.length>0?types.map(type=>buildItemSearchType(type,lowercasePaths)):EMPTY_GENERICS_ARRAY}const EMPTY_BINDINGS_MAP=new Map();const EMPTY_GENERICS_ARRAY=[];let TYPES_POOL=new Map();function buildItemSearchType(type,lowercasePaths,isAssocType){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;const BINDINGS_DATA=2;let pathIndex,generics,bindings;if(typeof type==="number"){pathIndex=type;generics=EMPTY_GENERICS_ARRAY;bindings=EMPTY_BINDINGS_MAP}else{pathIndex=type[PATH_INDEX_DATA];generics=buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths);if(type.length>BINDINGS_DATA&&type[BINDINGS_DATA].length>0){bindings=new Map(type[BINDINGS_DATA].map(binding=>{const[assocType,constraints]=binding;return[buildItemSearchType(assocType,lowercasePaths,true).id,buildItemSearchTypeAll(constraints,lowercasePaths),]}))}else{bindings=EMPTY_BINDINGS_MAP}}let result;if(pathIndex<0){result={id:pathIndex,ty:TY_GENERIC,path:null,generics,bindings,}}else if(pathIndex===0){result={id:null,ty:null,path:null,generics,bindings,}}else{const item=lowercasePaths[pathIndex-1];result={id:buildTypeMapIndex(item.name,isAssocType),ty:item.ty,path:item.path,generics,bindings,}}const cr=TYPES_POOL.get(result.id);if(cr){if(cr.generics.length===result.generics.length&&cr.generics!==result.generics&&cr.generics.every((x,i)=>result.generics[i]===x)){result.generics=cr.generics}if(cr.bindings.size===result.bindings.size&&cr.bindings!==result.bindings){let ok=true;for(const[k,v]of cr.bindings.entries()){const v2=result.bindings.get(v);if(!v2){ok=false;break}if(v!==v2&&v.length===v2.length&&v.every((x,i)=>v2[i]===x)){result.bindings.set(k,v)}else if(v!==v2){ok=false;break}}if(ok){result.bindings=cr.bindings}}if(cr.ty===result.ty&&cr.path===result.path&&cr.bindings===result.bindings&&cr.generics===result.generics&&cr.ty===result.ty){return cr}}TYPES_POOL.set(result.id,result);return result}function buildFunctionSearchType(itemFunctionDecoder,lowercasePaths){const c=itemFunctionDecoder.string.charCodeAt(itemFunctionDecoder.offset);itemFunctionDecoder.offset+=1;const[zero,ua,la,ob,cb]=["0","@","`","{","}"].map(c=>c.charCodeAt(0));if(c===la){return null}if(c>=zero&&c>1];itemFunctionDecoder.offset+=1;return sign?-value:value}const functionSearchType=decodeList();const INPUTS_DATA=0;const OUTPUT_DATA=1;let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){inputs=[buildItemSearchType(functionSearchType[INPUTS_DATA],lowercasePaths)]}else{inputs=buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){output=[buildItemSearchType(functionSearchType[OUTPUT_DATA],lowercasePaths)]}else{output=buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths)}}else{output=[]}const where_clause=[];const l=functionSearchType.length;for(let i=2;i16){itemFunctionDecoder.backrefQueue.pop()}return ret}function buildFunctionTypeFingerprint(type,output,fps){let input=type.id;if(input===typeNameIdOfArray||input===typeNameIdOfSlice){input=typeNameIdOfArrayOrSlice}if(input===typeNameIdOfTuple||input===typeNameIdOfUnit){input=typeNameIdOfTupleOrUnit}if(input===typeNameIdOfFn||input===typeNameIdOfFnMut||input===typeNameIdOfFnOnce){input=typeNameIdOfHof}const hashint1=k=>{k=(~~k+0x7ed55d16)+(k<<12);k=(k ^ 0xc761c23c)^(k>>>19);k=(~~k+0x165667b1)+(k<<5);k=(~~k+0xd3a2646c)^(k<<9);k=(~~k+0xfd7046c5)+(k<<3);return(k ^ 0xb55a4f09)^(k>>>16)};const hashint2=k=>{k=~k+(k<<15);k ^=k>>>12;k+=k<<2;k ^=k>>>4;k=Math.imul(k,2057);return k ^(k>>16)};if(input!==null){const h0a=hashint1(input);const h0b=hashint2(input);const h1a=~~(h0a+Math.imul(h0b,2));const h1b=~~(h0a+Math.imul(h0b,3));const h2a=~~(h0a+Math.imul(h0b,4));const h2b=~~(h0a+Math.imul(h0b,5));output[0]|=(1<<(h0a%32))|(1<<(h1b%32));output[1]|=(1<<(h1a%32))|(1<<(h2b%32));output[2]|=(1<<(h2a%32))|(1<<(h0b%32));fps.add(input)}for(const g of type.generics){buildFunctionTypeFingerprint(g,output,fps)}const fb={id:null,ty:0,generics:EMPTY_GENERICS_ARRAY,bindings:EMPTY_BINDINGS_MAP,};for(const[k,v]of type.bindings.entries()){fb.id=k;fb.generics=v;buildFunctionTypeFingerprint(fb,output,fps)}output[3]=fps.size}function compareTypeFingerprints(fullId,queryFingerprint){const fh0=functionTypeFingerprint[fullId*4];const fh1=functionTypeFingerprint[(fullId*4)+1];const fh2=functionTypeFingerprint[(fullId*4)+2];const[qh0,qh1,qh2]=queryFingerprint;const[in0,in1,in2]=[fh0&qh0,fh1&qh1,fh2&qh2];if((in0 ^ qh0)||(in1 ^ qh1)||(in2 ^ qh2)){return null}return functionTypeFingerprint[(fullId*4)+3]}function buildIndex(rawSearchIndex){searchIndex=[];const charA="A".charCodeAt(0);let currentIndex=0;let id=0;for(const crate of rawSearchIndex.values()){id+=crate.t.length+1}functionTypeFingerprint=new Uint32Array((id+1)*4);id=0;for(const[crate,crateCorpus]of rawSearchIndex){const crateRow={crate:crate,ty:3,name:crate,path:"",desc:crateCorpus.doc,parent:undefined,type:null,id:id,word:crate,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),deprecated:null,implDisambiguator:null,};id+=1;searchIndex.push(crateRow);currentIndex+=1;const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=new Map(crateCorpus.q);const itemDescs=crateCorpus.d;const itemParentIdxs=crateCorpus.i;const itemFunctionDecoder={string:crateCorpus.f,offset:0,backrefQueue:[],};const deprecatedItems=new Set(crateCorpus.c);const implDisambiguator=new Map(crateCorpus.b);const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];let len=paths.length;let lastPath=itemPaths.get(0);for(let i=0;i2){path=itemPaths.has(elem[2])?itemPaths.get(elem[2]):lastPath;lastPath=path}lowercasePaths.push({ty:ty,name:name.toLowerCase(),path:path});paths[i]={ty:ty,name:name,path:path}}lastPath="";len=itemTypes.length;for(let i=0;i0?paths[itemParentIdxs[i]-1]:undefined,type,id:id,word,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),deprecated:deprecatedItems.has(i),implDisambiguator:implDisambiguator.has(i)?implDisambiguator.get(i):null,};id+=1;searchIndex.push(row);lastPath=row.path}if(aliases){const currentCrateAliases=new Map();ALIASES.set(crate,currentCrateAliases);for(const alias_name in aliases){if(!Object.prototype.hasOwnProperty.call(aliases,alias_name)){continue}let currentNameAliases;if(currentCrateAliases.has(alias_name)){currentNameAliases=currentCrateAliases.get(alias_name)}else{currentNameAliases=[];currentCrateAliases.set(alias_name,currentNameAliases)}for(const local_alias of aliases[alias_name]){currentNameAliases.push(local_alias+currentIndex)}}}currentIndex+=itemTypes.length}TYPES_POOL=new Map()}function onSearchSubmit(e){e.preventDefault();searchState.clearInputTimeout();search()}function putBackSearch(){const search_input=searchState.input;if(!searchState.input){return}if(search_input.value!==""&&!searchState.isDisplayed()){searchState.showResults();if(browserSupportsHistoryApi()){history.replaceState(null,"",buildUrl(search_input.value,getFilterCrates()))}document.title=searchState.title}}function registerSearchEvents(){const params=searchState.getQueryStringParams();if(searchState.input.value===""){searchState.input.value=params.search||""}const searchAfter500ms=()=>{searchState.clearInputTimeout();if(searchState.input.value.length===0){searchState.hideResults()}else{searchState.timeout=setTimeout(search,500)}};searchState.input.onkeyup=searchAfter500ms;searchState.input.oninput=searchAfter500ms;document.getElementsByClassName("search-form")[0].onsubmit=onSearchSubmit;searchState.input.onchange=e=>{if(e.target!==document.activeElement){return}searchState.clearInputTimeout();setTimeout(search,0)};searchState.input.onpaste=searchState.input.onchange;searchState.outputElement().addEventListener("keydown",e=>{if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey){return}if(e.which===38){const previous=document.activeElement.previousElementSibling;if(previous){previous.focus()}else{searchState.focus()}e.preventDefault()}else if(e.which===40){const next=document.activeElement.nextElementSibling;if(next){next.focus()}const rect=document.activeElement.getBoundingClientRect();if(window.innerHeight-rect.bottom{if(e.which===40){focusSearchResult();e.preventDefault()}});searchState.input.addEventListener("focus",()=>{putBackSearch()});searchState.input.addEventListener("blur",()=>{searchState.input.placeholder=searchState.input.origPlaceholder});if(browserSupportsHistoryApi()){const previousTitle=document.title;window.addEventListener("popstate",e=>{const params=searchState.getQueryStringParams();document.title=previousTitle;currentResults=null;if(params.search&¶ms.search.length>0){searchState.input.value=params.search;e.preventDefault();search()}else{searchState.input.value="";searchState.hideResults()}})}window.onpageshow=()=>{const qSearch=searchState.getQueryStringParams().search;if(searchState.input.value===""&&qSearch){searchState.input.value=qSearch}search()}}function updateCrate(ev){if(ev.target.value==="all crates"){const query=searchState.input.value.trim();updateSearchHistory(buildUrl(query,null))}currentResults=null;search(true)}buildIndex(rawSearchIndex);if(typeof window!=="undefined"){registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}if(typeof exports!=="undefined"){exports.initSearch=initSearch;exports.execQuery=execQuery;exports.parseQuery=parseQuery}}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch(new Map())}})() \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/settings-4313503d2e1961c2.js b/Documentation/RustDoc/static.files/settings-4313503d2e1961c2.js new file mode 100644 index 00000000..ab425fe4 --- /dev/null +++ b/Documentation/RustDoc/static.files/settings-4313503d2e1961c2.js @@ -0,0 +1,17 @@ +"use strict";(function(){const isSettingsPage=window.location.pathname.endsWith("/settings.html");function changeSetting(settingName,value){if(settingName==="theme"){const useSystem=value==="system preference"?"true":"false";updateLocalStorage("use-system-theme",useSystem)}updateLocalStorage(settingName,value);switch(settingName){case"theme":case"preferred-dark-theme":case"preferred-light-theme":updateTheme();updateLightAndDark();break;case"line-numbers":if(value===true){window.rustdoc_add_line_numbers_to_examples()}else{window.rustdoc_remove_line_numbers_from_examples()}break;case"hide-sidebar":if(value===true){addClass(document.documentElement,"hide-sidebar")}else{removeClass(document.documentElement,"hide-sidebar")}break}}function showLightAndDark(){removeClass(document.getElementById("preferred-light-theme"),"hidden");removeClass(document.getElementById("preferred-dark-theme"),"hidden")}function hideLightAndDark(){addClass(document.getElementById("preferred-light-theme"),"hidden");addClass(document.getElementById("preferred-dark-theme"),"hidden")}function updateLightAndDark(){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||(useSystem===null&&getSettingValue("theme")===null)){showLightAndDark()}else{hideLightAndDark()}}function setEvents(settingsElement){updateLightAndDark();onEachLazy(settingsElement.querySelectorAll("input[type=\"checkbox\"]"),toggle=>{const settingId=toggle.id;const settingValue=getSettingValue(settingId);if(settingValue!==null){toggle.checked=settingValue==="true"}toggle.onchange=()=>{changeSetting(toggle.id,toggle.checked)}});onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"),elem=>{const settingId=elem.name;let settingValue=getSettingValue(settingId);if(settingId==="theme"){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||settingValue===null){settingValue=useSystem==="false"?"light":"system preference"}}if(settingValue!==null&&settingValue!=="null"){elem.checked=settingValue===elem.value}elem.addEventListener("change",ev=>{changeSetting(ev.target.name,ev.target.value)})})}function buildSettingsPageSections(settings){let output="";for(const setting of settings){const js_data_name=setting["js_name"];const setting_name=setting["name"];if(setting["options"]!==undefined){output+=`\ +
    +
    ${setting_name}
    +
    `;onEach(setting["options"],option=>{const checked=option===setting["default"]?" checked":"";const full=`${js_data_name}-${option.replace(/ /g,"-")}`;output+=`\ + `});output+=`\ +
    +
    `}else{const checked=setting["default"]===true?" checked":"";output+=`\ +
    \ + \ +
    `}}return output}function buildSettingsPage(){const theme_names=getVar("themes").split(",").filter(t=>t);theme_names.push("light","dark","ayu");const settings=[{"name":"Theme","js_name":"theme","default":"system preference","options":theme_names.concat("system preference"),},{"name":"Preferred light theme","js_name":"preferred-light-theme","default":"light","options":theme_names,},{"name":"Preferred dark theme","js_name":"preferred-dark-theme","default":"dark","options":theme_names,},{"name":"Auto-hide item contents for large items","js_name":"auto-hide-large-items","default":true,},{"name":"Auto-hide item methods' documentation","js_name":"auto-hide-method-docs","default":false,},{"name":"Auto-hide trait implementation documentation","js_name":"auto-hide-trait-implementations","default":false,},{"name":"Directly go to item in search if there is only one result","js_name":"go-to-only-result","default":false,},{"name":"Show line numbers on code examples","js_name":"line-numbers","default":false,},{"name":"Hide persistent navigation bar","js_name":"hide-sidebar","default":false,},{"name":"Disable keyboard shortcuts","js_name":"disable-shortcuts","default":false,},];const elementKind=isSettingsPage?"section":"div";const innerHTML=`
    ${buildSettingsPageSections(settings)}
    `;const el=document.createElement(elementKind);el.id="settings";if(!isSettingsPage){el.className="popover"}el.innerHTML=innerHTML;if(isSettingsPage){document.getElementById(MAIN_ID).appendChild(el)}else{el.setAttribute("tabindex","-1");getSettingsButton().appendChild(el)}return el}const settingsMenu=buildSettingsPage();function displaySettings(){settingsMenu.style.display="";onEachLazy(settingsMenu.querySelectorAll("input[type='checkbox']"),el=>{const val=getSettingValue(el.id);const checked=val==="true";if(checked!==el.checked&&val!==null){el.checked=checked}})}function settingsBlurHandler(event){blurHandler(event,getSettingsButton(),window.hidePopoverMenus)}if(isSettingsPage){getSettingsButton().onclick=event=>{event.preventDefault()}}else{const settingsButton=getSettingsButton();const settingsMenu=document.getElementById("settings");settingsButton.onclick=event=>{if(settingsMenu.contains(event.target)){return}event.preventDefault();const shouldDisplaySettings=settingsMenu.style.display==="none";window.hideAllModals();if(shouldDisplaySettings){displaySettings()}};settingsButton.onblur=settingsBlurHandler;settingsButton.querySelector("a").onblur=settingsBlurHandler;onEachLazy(settingsMenu.querySelectorAll("input"),el=>{el.onblur=settingsBlurHandler});settingsMenu.onblur=settingsBlurHandler}setTimeout(()=>{setEvents(settingsMenu);if(!isSettingsPage){displaySettings()}removeClass(getSettingsButton(),"rotate")},0)})() \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/src-script-e66d777a5a92e9b2.js b/Documentation/RustDoc/static.files/src-script-e66d777a5a92e9b2.js new file mode 100644 index 00000000..d0aebb85 --- /dev/null +++ b/Documentation/RustDoc/static.files/src-script-e66d777a5a92e9b2.js @@ -0,0 +1 @@ +"use strict";(function(){const rootPath=getVar("root-path");const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;const RUSTDOC_MOBILE_BREAKPOINT=700;function closeSidebarIfMobile(){if(window.innerWidth{removeClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","false")};window.rustdocShowSourceSidebar=()=>{addClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","true")};window.rustdocToggleSrcSidebar=()=>{if(document.documentElement.classList.contains("src-sidebar-expanded")){window.rustdocCloseSourceSidebar()}else{window.rustdocShowSourceSidebar()}};function createSrcSidebar(){const container=document.querySelector("nav.sidebar");const sidebar=document.createElement("div");sidebar.id="src-sidebar";let hasFoundFile=false;for(const[key,source]of srcIndex){source[NAME_OFFSET]=key;hasFoundFile=createDirEntry(source,sidebar,"",hasFoundFile)}container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}function highlightSrcLines(){const match=window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);if(!match){return}let from=parseInt(match[1],10);let to=from;if(typeof match[2]!=="undefined"){to=parseInt(match[2],10)}if(to{onEachLazy(e.getElementsByTagName("a"),i_e=>{removeClass(i_e,"line-highlighted")})});for(let i=from;i<=to;++i){elem=document.getElementById(i);if(!elem){break}addClass(elem,"line-highlighted")}}const handleSrcHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSrcLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)||ev.ctrlKey||ev.altKey||ev.metaKey){return}ev.preventDefault();if(ev.shiftKey&&prev_line_id){if(prev_line_id>cur_line_id){const tmp=prev_line_id;prev_line_id=cur_line_id;cur_line_id=tmp}set_fragment(prev_line_id+"-"+cur_line_id)}else{prev_line_id=cur_line_id;set_fragment(cur_line_id)}}}());window.addEventListener("hashchange",highlightSrcLines);onEachLazy(document.getElementsByClassName("src-line-numbers"),el=>{el.addEventListener("click",handleSrcHighlight)});highlightSrcLines();window.createSrcSidebar=createSrcSidebar})() \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/storage-4c98445ec4002617.js b/Documentation/RustDoc/static.files/storage-4c98445ec4002617.js new file mode 100644 index 00000000..b378b856 --- /dev/null +++ b/Documentation/RustDoc/static.files/storage-4c98445ec4002617.js @@ -0,0 +1 @@ +"use strict";const builtinThemes=["light","dark","ayu"];const darkThemes=["dark","ayu"];window.currentTheme=document.getElementById("themeStyle");const settingsDataset=(function(){const settingsElement=document.getElementById("default-settings");return settingsElement&&settingsElement.dataset?settingsElement.dataset:null})();function getSettingValue(settingName){const current=getCurrentValue(settingName);if(current===null&&settingsDataset!==null){const def=settingsDataset[settingName.replace(/-/g,"_")];if(def!==undefined){return def}}return current}const localStoredTheme=getSettingValue("theme");function hasClass(elem,className){return elem&&elem.classList&&elem.classList.contains(className)}function addClass(elem,className){if(elem&&elem.classList){elem.classList.add(className)}}function removeClass(elem,className){if(elem&&elem.classList){elem.classList.remove(className)}}function onEach(arr,func){for(const elem of arr){if(func(elem)){return true}}return false}function onEachLazy(lazyArray,func){return onEach(Array.prototype.slice.call(lazyArray),func)}function updateLocalStorage(name,value){try{window.localStorage.setItem("rustdoc-"+name,value)}catch(e){}}function getCurrentValue(name){try{return window.localStorage.getItem("rustdoc-"+name)}catch(e){return null}}const getVar=(function getVar(name){const el=document.querySelector("head > meta[name='rustdoc-vars']");return el?el.attributes["data-"+name].value:null});function switchTheme(newThemeName,saveTheme){const themeNames=getVar("themes").split(",").filter(t=>t);themeNames.push(...builtinThemes);if(themeNames.indexOf(newThemeName)===-1){return}if(saveTheme){updateLocalStorage("theme",newThemeName)}document.documentElement.setAttribute("data-theme",newThemeName);if(builtinThemes.indexOf(newThemeName)!==-1){if(window.currentTheme){window.currentTheme.parentNode.removeChild(window.currentTheme);window.currentTheme=null}}else{const newHref=getVar("root-path")+encodeURIComponent(newThemeName)+getVar("resource-suffix")+".css";if(!window.currentTheme){if(document.readyState==="loading"){document.write(``);window.currentTheme=document.getElementById("themeStyle")}else{window.currentTheme=document.createElement("link");window.currentTheme.rel="stylesheet";window.currentTheme.id="themeStyle";window.currentTheme.href=newHref;document.documentElement.appendChild(window.currentTheme)}}else if(newHref!==window.currentTheme.href){window.currentTheme.href=newHref}}}const updateTheme=(function(){const mql=window.matchMedia("(prefers-color-scheme: dark)");function updateTheme(){if(getSettingValue("use-system-theme")!=="false"){const lightTheme=getSettingValue("preferred-light-theme")||"light";const darkTheme=getSettingValue("preferred-dark-theme")||"dark";updateLocalStorage("use-system-theme","true");switchTheme(mql.matches?darkTheme:lightTheme,true)}else{switchTheme(getSettingValue("theme"),false)}}mql.addEventListener("change",updateTheme);return updateTheme})();if(getSettingValue("use-system-theme")!=="false"&&window.matchMedia){if(getSettingValue("use-system-theme")===null&&getSettingValue("preferred-dark-theme")===null&&darkThemes.indexOf(localStoredTheme)>=0){updateLocalStorage("preferred-dark-theme",localStoredTheme)}}updateTheme();if(getSettingValue("source-sidebar-show")==="true"){addClass(document.documentElement,"src-sidebar-expanded")}if(getSettingValue("hide-sidebar")==="true"){addClass(document.documentElement,"hide-sidebar")}function updateSidebarWidth(){const desktopSidebarWidth=getSettingValue("desktop-sidebar-width");if(desktopSidebarWidth&&desktopSidebarWidth!=="null"){document.documentElement.style.setProperty("--desktop-sidebar-width",desktopSidebarWidth+"px")}const srcSidebarWidth=getSettingValue("src-sidebar-width");if(srcSidebarWidth&&srcSidebarWidth!=="null"){document.documentElement.style.setProperty("--src-sidebar-width",srcSidebarWidth+"px")}}updateSidebarWidth();window.addEventListener("pageshow",ev=>{if(ev.persisted){setTimeout(updateTheme,0);setTimeout(updateSidebarWidth,0)}}) \ No newline at end of file diff --git a/Documentation/RustDoc/static.files/wheel-7b819b6101059cd0.svg b/Documentation/RustDoc/static.files/wheel-7b819b6101059cd0.svg new file mode 100644 index 00000000..83c07f63 --- /dev/null +++ b/Documentation/RustDoc/static.files/wheel-7b819b6101059cd0.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/clone/trait.Clone.js b/Documentation/RustDoc/trait.impl/core/clone/trait.Clone.js new file mode 100644 index 00000000..74cb7dfb --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/clone/trait.Clone.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Clone for AsymmetricEncryption"],["impl Clone for BlockCiphers"],["impl Clone for EccCurves"],["impl Clone for EccSchemeAlgorithm"],["impl Clone for Rc2KeyBits"],["impl Clone for StreamCiphers"],["impl Clone for SymmetricMode"],["impl Clone for TripleDesNumKeys"],["impl Clone for KeyBits"],["impl Clone for Hash"],["impl Clone for Sha2Bits"],["impl Clone for Sha3Bits"],["impl Clone for KeyUsage"],["impl Clone for SecurityModule"],["impl Clone for EncryptionMode"],["impl Clone for AndroidTpmType"],["impl Clone for TpmType"],["impl Clone for TpmConfig"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/cmp/trait.Eq.js b/Documentation/RustDoc/trait.impl/core/cmp/trait.Eq.js new file mode 100644 index 00000000..5e4043c3 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/cmp/trait.Eq.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Eq for EccCurves"],["impl Eq for EccSchemeAlgorithm"],["impl Eq for KeyUsage"],["impl Eq for SecurityModule"],["impl Eq for AndroidTpmType"],["impl Eq for TpmType"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/cmp/trait.PartialEq.js b/Documentation/RustDoc/trait.impl/core/cmp/trait.PartialEq.js new file mode 100644 index 00000000..7f87cfbd --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/cmp/trait.PartialEq.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl PartialEq for EccCurves"],["impl PartialEq for EccSchemeAlgorithm"],["impl PartialEq for KeyUsage"],["impl PartialEq for SecurityModule"],["impl PartialEq for AndroidTpmType"],["impl PartialEq for TpmType"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/convert/trait.From.js b/Documentation/RustDoc/trait.impl/core/convert/trait.From.js new file mode 100644 index 00000000..16a19ca5 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/convert/trait.From.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl From<&str> for SecurityModule"],["impl From<&str> for TpmType"],["impl From<KeyBits> for u32"],["impl From<Sha2Bits> for u32"],["impl From<Sha3Bits> for u32"],["impl From<TpmError> for SecurityModuleError"],["impl From<u32> for KeyBits"],["impl From<u32> for Sha2Bits"],["impl From<u32> for Sha3Bits"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/default/trait.Default.js b/Documentation/RustDoc/trait.impl/core/default/trait.Default.js new file mode 100644 index 00000000..38f83b49 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/default/trait.Default.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Default for AsymmetricEncryption"],["impl Default for BlockCiphers"],["impl Default for EccCurves"],["impl Default for EccSchemeAlgorithm"],["impl Default for SymmetricMode"],["impl Default for Hash"],["impl Default for TpmType"],["impl Default for TpmConfig"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/error/trait.Error.js b/Documentation/RustDoc/trait.impl/core/error/trait.Error.js new file mode 100644 index 00000000..d6dc5015 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/error/trait.Error.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Error for SecurityModuleError"],["impl Error for TpmError"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/fmt/trait.Debug.js b/Documentation/RustDoc/trait.impl/core/fmt/trait.Debug.js new file mode 100644 index 00000000..846bfec1 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/fmt/trait.Debug.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Debug for AsymmetricEncryption"],["impl Debug for BlockCiphers"],["impl Debug for EccCurves"],["impl Debug for EccSchemeAlgorithm"],["impl Debug for Rc2KeyBits"],["impl Debug for SymmetricMode"],["impl Debug for TripleDesNumKeys"],["impl Debug for KeyBits"],["impl Debug for Hash"],["impl Debug for Sha2Bits"],["impl Debug for Sha3Bits"],["impl Debug for KeyUsage"],["impl Debug for SecurityModuleError"],["impl Debug for SecurityModule"],["impl Debug for EncryptionMode"],["impl Debug for TpmError"],["impl Debug for AndroidTpmType"],["impl Debug for TpmType"],["impl Debug for DefaultAndroidLogger"],["impl Debug for AndroidConfig"],["impl Debug for KnoxConfig"],["impl Debug for KnoxProvider"],["impl Debug for TpmConfig"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/fmt/trait.Display.js b/Documentation/RustDoc/trait.impl/core/fmt/trait.Display.js new file mode 100644 index 00000000..d0a71440 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/fmt/trait.Display.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Display for SecurityModuleError"],["impl Display for TpmError"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/hash/trait.Hash.js b/Documentation/RustDoc/trait.impl/core/hash/trait.Hash.js new file mode 100644 index 00000000..b7f681f1 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/hash/trait.Hash.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Hash for EccCurves"],["impl Hash for EccSchemeAlgorithm"],["impl Hash for KeyUsage"],["impl Hash for SecurityModule"],["impl Hash for AndroidTpmType"],["impl Hash for TpmType"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.Copy.js b/Documentation/RustDoc/trait.impl/core/marker/trait.Copy.js new file mode 100644 index 00000000..7b6b776c --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.Copy.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Copy for AsymmetricEncryption"],["impl Copy for BlockCiphers"],["impl Copy for EccCurves"],["impl Copy for EccSchemeAlgorithm"],["impl Copy for Rc2KeyBits"],["impl Copy for SymmetricMode"],["impl Copy for TripleDesNumKeys"],["impl Copy for KeyBits"],["impl Copy for Hash"],["impl Copy for Sha2Bits"],["impl Copy for Sha3Bits"],["impl Copy for KeyUsage"],["impl Copy for EncryptionMode"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.Freeze.js b/Documentation/RustDoc/trait.impl/core/marker/trait.Freeze.js new file mode 100644 index 00000000..c70e4b61 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.Freeze.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Freeze for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl Freeze for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl Freeze for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl Freeze for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl Freeze for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl Freeze for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl Freeze for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl Freeze for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl Freeze for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl Freeze for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl Freeze for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl Freeze for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl Freeze for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl Freeze for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl Freeze for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl Freeze for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl Freeze for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl Freeze for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl Freeze for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl Freeze for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl Freeze for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl Freeze for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl Freeze for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl Freeze for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl Freeze for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl Freeze for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl Freeze for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl Freeze for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl Freeze for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl Freeze for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl Freeze for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.Send.js b/Documentation/RustDoc/trait.impl/core/marker/trait.Send.js new file mode 100644 index 00000000..ed761105 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.Send.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl !Send for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl !Send for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl Send for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl Send for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl Send for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl Send for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl Send for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl Send for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl Send for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl Send for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl Send for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl Send for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl Send for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl Send for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl Send for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl Send for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl Send for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl Send for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl Send for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl Send for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl Send for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl Send for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl Send for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl Send for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl Send for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl Send for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl Send for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl Send for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl Send for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl Send for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl Send for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.StructuralPartialEq.js b/Documentation/RustDoc/trait.impl/core/marker/trait.StructuralPartialEq.js new file mode 100644 index 00000000..d36cf1ec --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.StructuralPartialEq.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl StructuralPartialEq for EccCurves"],["impl StructuralPartialEq for EccSchemeAlgorithm"],["impl StructuralPartialEq for KeyUsage"],["impl StructuralPartialEq for SecurityModule"],["impl StructuralPartialEq for AndroidTpmType"],["impl StructuralPartialEq for TpmType"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.Sync.js b/Documentation/RustDoc/trait.impl/core/marker/trait.Sync.js new file mode 100644 index 00000000..9db4a5d6 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.Sync.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl !Sync for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl !Sync for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl Sync for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl Sync for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl Sync for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl Sync for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl Sync for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl Sync for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl Sync for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl Sync for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl Sync for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl Sync for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl Sync for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl Sync for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl Sync for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl Sync for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl Sync for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl Sync for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl Sync for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl Sync for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl Sync for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl Sync for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl Sync for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl Sync for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl Sync for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl Sync for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl Sync for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl Sync for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl Sync for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl Sync for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl Sync for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/marker/trait.Unpin.js b/Documentation/RustDoc/trait.impl/core/marker/trait.Unpin.js new file mode 100644 index 00000000..0f9ed408 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/marker/trait.Unpin.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Unpin for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl Unpin for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl Unpin for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl Unpin for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl Unpin for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl Unpin for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl Unpin for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl Unpin for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl Unpin for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl Unpin for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl Unpin for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl Unpin for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl Unpin for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl Unpin for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl Unpin for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl Unpin for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl Unpin for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl Unpin for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl Unpin for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl Unpin for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl Unpin for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl Unpin for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl Unpin for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl Unpin for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl Unpin for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl Unpin for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl Unpin for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl Unpin for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl Unpin for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl Unpin for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl Unpin for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js new file mode 100644 index 00000000..150b195b --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl !RefUnwindSafe for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl !RefUnwindSafe for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl !RefUnwindSafe for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl RefUnwindSafe for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl RefUnwindSafe for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl RefUnwindSafe for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl RefUnwindSafe for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl RefUnwindSafe for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl RefUnwindSafe for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl RefUnwindSafe for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl RefUnwindSafe for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl RefUnwindSafe for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl RefUnwindSafe for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl RefUnwindSafe for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl RefUnwindSafe for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl RefUnwindSafe for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl RefUnwindSafe for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl RefUnwindSafe for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl RefUnwindSafe for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl RefUnwindSafe for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl RefUnwindSafe for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl RefUnwindSafe for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl RefUnwindSafe for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl RefUnwindSafe for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl RefUnwindSafe for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl RefUnwindSafe for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl RefUnwindSafe for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl RefUnwindSafe for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl RefUnwindSafe for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl RefUnwindSafe for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl RefUnwindSafe for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js new file mode 100644 index 00000000..171c63d6 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl !UnwindSafe for SecurityModuleError",1,["crypto_layer::common::error::SecurityModuleError"]],["impl !UnwindSafe for TpmError",1,["crypto_layer::tpm::core::error::TpmError"]],["impl !UnwindSafe for TpmInstance",1,["crypto_layer::tpm::core::instance::TpmInstance"]],["impl UnwindSafe for AsymmetricEncryption",1,["crypto_layer::common::crypto::algorithms::encryption::AsymmetricEncryption"]],["impl UnwindSafe for BlockCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::BlockCiphers"]],["impl UnwindSafe for EccCurves",1,["crypto_layer::common::crypto::algorithms::encryption::EccCurves"]],["impl UnwindSafe for EccSchemeAlgorithm",1,["crypto_layer::common::crypto::algorithms::encryption::EccSchemeAlgorithm"]],["impl UnwindSafe for Rc2KeyBits",1,["crypto_layer::common::crypto::algorithms::encryption::Rc2KeyBits"]],["impl UnwindSafe for StreamCiphers",1,["crypto_layer::common::crypto::algorithms::encryption::StreamCiphers"]],["impl UnwindSafe for SymmetricMode",1,["crypto_layer::common::crypto::algorithms::encryption::SymmetricMode"]],["impl UnwindSafe for TripleDesNumKeys",1,["crypto_layer::common::crypto::algorithms::encryption::TripleDesNumKeys"]],["impl UnwindSafe for KeyBits",1,["crypto_layer::common::crypto::algorithms::KeyBits"]],["impl UnwindSafe for Hash",1,["crypto_layer::common::crypto::algorithms::hashes::Hash"]],["impl UnwindSafe for Sha2Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha2Bits"]],["impl UnwindSafe for Sha3Bits",1,["crypto_layer::common::crypto::algorithms::hashes::Sha3Bits"]],["impl UnwindSafe for KeyUsage",1,["crypto_layer::common::crypto::KeyUsage"]],["impl UnwindSafe for ObjectIdentifiers",1,["crypto_layer::common::crypto::pkcs::standards::ObjectIdentifiers"]],["impl UnwindSafe for OidType",1,["crypto_layer::common::crypto::pkcs::standards::OidType"]],["impl UnwindSafe for PkcsType",1,["crypto_layer::common::crypto::pkcs::standards::PkcsType"]],["impl UnwindSafe for PkiStandards",1,["crypto_layer::common::crypto::pkcs::standards::PkiStandards"]],["impl UnwindSafe for X509Type",1,["crypto_layer::common::crypto::pkcs::standards::X509Type"]],["impl UnwindSafe for SecurityModule",1,["crypto_layer::common::factory::SecurityModule"]],["impl UnwindSafe for EncryptionMode",1,["crypto_layer::tpm::android::config::EncryptionMode"]],["impl UnwindSafe for AndroidTpmType",1,["crypto_layer::tpm::core::instance::AndroidTpmType"]],["impl UnwindSafe for TpmType",1,["crypto_layer::tpm::core::instance::TpmType"]],["impl UnwindSafe for SecModules",1,["crypto_layer::common::factory::SecModules"]],["impl UnwindSafe for DefaultAndroidLogger",1,["crypto_layer::tpm::android::android_logger::DefaultAndroidLogger"]],["impl UnwindSafe for AndroidConfig",1,["crypto_layer::tpm::android::config::AndroidConfig"]],["impl UnwindSafe for KnoxConfig",1,["crypto_layer::tpm::android::knox::KnoxConfig"]],["impl UnwindSafe for KnoxProvider",1,["crypto_layer::tpm::android::knox::KnoxProvider"]],["impl UnwindSafe for TpmConfig",1,["crypto_layer::tpm::TpmConfig"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/key_handle/trait.KeyHandle.js b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/key_handle/trait.KeyHandle.js new file mode 100644 index 00000000..165ff3e2 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/key_handle/trait.KeyHandle.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/log_config/trait.LogConfig.js b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/log_config/trait.LogConfig.js new file mode 100644 index 00000000..165ff3e2 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/log_config/trait.LogConfig.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider/trait.Provider.js b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider/trait.Provider.js new file mode 100644 index 00000000..165ff3e2 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider/trait.Provider.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.js b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.js new file mode 100644 index 00000000..165ff3e2 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/crypto_layer/common/traits/module_provider_config/trait.ProviderConfig.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/crypto_layer/tpm/core/error/trait.ToTpmError.js b/Documentation/RustDoc/trait.impl/crypto_layer/tpm/core/error/trait.ToTpmError.js new file mode 100644 index 00000000..165ff3e2 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/crypto_layer/tpm/core/error/trait.ToTpmError.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/serde/de/trait.Deserialize.js b/Documentation/RustDoc/trait.impl/serde/de/trait.Deserialize.js new file mode 100644 index 00000000..8117f367 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/serde/de/trait.Deserialize.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl<'de> Deserialize<'de> for EccCurves"],["impl<'de> Deserialize<'de> for EccSchemeAlgorithm"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/RustDoc/trait.impl/serde/ser/trait.Serialize.js b/Documentation/RustDoc/trait.impl/serde/ser/trait.Serialize.js new file mode 100644 index 00000000..e1448854 --- /dev/null +++ b/Documentation/RustDoc/trait.impl/serde/ser/trait.Serialize.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"crypto_layer":[["impl Serialize for EccCurves"],["impl Serialize for EccSchemeAlgorithm"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/Documentation/resources/Cargo.toml b/Documentation/resources/Cargo.toml new file mode 100644 index 00000000..d89cbe5d --- /dev/null +++ b/Documentation/resources/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "your_project_name" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] +path = "lib.rs" + +[dependencies] +robusta_jni = "0.2" +jni = "^0.20" +android_logger = "^0" +log = "^0" +crypto-layer = { path = "../rust-crypto-knox", features = ["android", "tpm"] } \ No newline at end of file diff --git a/Documentation/resources/component_diagram.jpg b/Documentation/resources/component_diagram.jpg new file mode 100644 index 00000000..83029751 Binary files /dev/null and b/Documentation/resources/component_diagram.jpg differ diff --git a/Documentation/resources/lib.rs b/Documentation/resources/lib.rs new file mode 100644 index 00000000..6855b91f --- /dev/null +++ b/Documentation/resources/lib.rs @@ -0,0 +1,25 @@ +use robusta_jni::bridge; +#[bridge] +pub mod jni { + use robusta_jni::{ + convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue}, + jni::{ + JNIEnv, + objects::AutoLocal, + }, + }; + #[allow(unused_imports)] //the bridge import is marked as unused, but if removed the compiler throws an error + use robusta_jni::bridge; + #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)] + #[package(com.example.test_1inst_1guide)] //the 1 is an escape character for the underscore + pub struct RustDef<'env: 'borrow, 'borrow> { + #[instance] + pub raw: AutoLocal<'env, 'borrow>, + } + + #[allow(non_snake_case)] + impl<'env: 'borrow, 'borrow> RustDef<'env, 'borrow> { + + pub extern "jni" fn callRust(environment: &JNIEnv) -> String { String::from("Hello from Rust!") } + } +} \ No newline at end of file diff --git a/Documentation/resources/method_call_structure.png b/Documentation/resources/method_call_structure.png new file mode 100644 index 00000000..23a59a8e Binary files /dev/null and b/Documentation/resources/method_call_structure.png differ diff --git a/src/common/error.rs b/src/common/error.rs index 0bfb6c36..72fa6304 100644 --- a/src/common/error.rs +++ b/src/common/error.rs @@ -43,6 +43,10 @@ pub enum SecurityModuleError { /// /// This variant contains a descriptive error message. InitializationError(String), + /// Error that occurred during the key generation operation. + /// + /// This variant contains a descriptive error message. + CreationError(String), KeyError, UnsupportedAlgorithm, VerificationFailed, @@ -81,6 +85,10 @@ impl fmt::Display for SecurityModuleError { SecurityModuleError::InitializationError(ref error_msg) => { write!(f, "Initialization error: {}", error_msg) } + + SecurityModuleError::CreationError(ref error_msg) => { + write!(f, "Creation error: {}", error_msg) + } SecurityModuleError::KeyError => write!(f, "Key error"), SecurityModuleError::UnsupportedAlgorithm => write!(f, "Unsupported algorithm"), SecurityModuleError::VerificationFailed => write!(f, "Verification failed"), @@ -113,6 +121,7 @@ impl std::error::Error for SecurityModuleError { SecurityModuleError::EncryptionError(_) => None, SecurityModuleError::SignatureVerificationError(_) => None, SecurityModuleError::InitializationError(_) => None, + SecurityModuleError::CreationError(_) => None SecurityModuleError::KeyError => None, SecurityModuleError::UnsupportedAlgorithm => None, SecurityModuleError::VerificationFailed => None, diff --git a/src/tests/common/traits/mod.rs b/src/tests/common/traits/mod.rs index fd907b57..090fda08 100644 --- a/src/tests/common/traits/mod.rs +++ b/src/tests/common/traits/mod.rs @@ -2,12 +2,16 @@ use tracing::Level; use tracing_appender::rolling; use tracing_subscriber::FmtSubscriber; +#[cfg(feature = "tpm")] +use crate::tpm::core::instance::TpmType; +#[cfg(feature = "tpm")] +use crate::tpm::linux::TpmProvider; use crate::{ common::{ factory::SecurityModule, traits::{log_config::LogConfig, module_provider::Provider}, }, - tpm::core::instance::TpmType, + // tpm::core::instance::TpmType, SecModules, }; use std::sync::{Arc, Mutex}; @@ -37,7 +41,7 @@ impl LogConfig for Logger { } } -fn setup_security_module(module: SecurityModule) -> Arc> { +pub fn setup_security_module(module: SecurityModule) -> Arc> { let log = Logger::new_boxed(); match module { #[cfg(feature = "hsm")] @@ -58,8 +62,15 @@ fn setup_security_module(module: SecurityModule) -> Arc> { Some(log), ) .unwrap(), + TpmType::Android(t) => SecModules::get_instance( + "test_key".to_owned(), + SecurityModule::Tpm(TpmType::Android(t)), + Some(log), + ) + .unwrap(), TpmType::None => unimplemented!(), - TpmType::Android(_) => unimplemented!(), + + _ => unimplemented!(), }, #[cfg(feature = "nks")] SecurityModule::Nks => unimplemented!(), diff --git a/src/tpm/android/knox/README.md b/src/tpm/android/knox/README.md new file mode 100644 index 00000000..96afc627 --- /dev/null +++ b/src/tpm/android/knox/README.md @@ -0,0 +1,18 @@ +## rust-crypto-knox +Welcome! Here you will find a wrapper that is used to perform cryptographic operations for mobile applications on an Android devices Secure Element (SE), specifically focused on Samsung Knox Vault. The interface to the mobile application is provided in Rust, while the communication with the SE is done using the Android Keystore System. + +### Functions +Our wrapper has the following functionalities implemented: +- generating and loading keys with a smartphones Secure Element +- encrypting and decrypting with a symmetric key +- signing and verifying with an asymmetric key + +For more specific information (e.g. supported cryptographic algorithms) please refer to the documentation linked below. + +### Installation and Documentation + +For an installation guide, please refer to [the Documentation](../../../../Documentation/Doc.md). + +### Contribution Guidelines +Contributions to the Crypto Layer are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the project's GitHub repository. +The contribution guidelines are as per the guide [HERE](https://github.com/nmshd/.github/blob/main/CONTRIBUTING.md). diff --git a/src/tpm/android/knox/interface.rs b/src/tpm/android/knox/interface.rs new file mode 100644 index 00000000..fc1b0f5f --- /dev/null +++ b/src/tpm/android/knox/interface.rs @@ -0,0 +1,366 @@ +use robusta_jni::bridge; + + +#[bridge] +pub mod jni { + #[allow(unused_imports)] //the bridge import is marked as unused, but if removed the compiler throws an error + use robusta_jni::{ + bridge, + convert::{IntoJavaValue, Signature, TryFromJavaValue, TryIntoJavaValue}, + jni::{ + errors::Error, + JNIEnv, + objects::{ + AutoLocal, + JValue + }, + sys::jbyteArray + }, + }; + + use crate::SecurityModuleError; + + const CLASS_SIGNATURE: &str = "com/example/vulcans_limes/RustDef"; + + /// Contains all methods related to Rust - Java communication and the JNI + #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)] + #[package(com.example.vulcans_1limes)] //the 1 after the "_" is an escape character for the "_" + pub struct RustDef<'env: 'borrow, 'borrow> { + #[instance] + pub raw: AutoLocal<'env, 'borrow>, + } + + + /// This Implementation provides the method declarations that are the interface for the JNI. + /// The first part contains Java-methods that can be called from Rust. + /// The second part contains some utility methods. + /// + /// All method signatures have to correspond to their counterparts in RustDef.java, with the + /// same method name and corresponding parameters according to this table: + /// | **Rust** | **Java** | + /// |----------------------------------------------------|-----------------------------------| + /// | i32 | int | + /// | bool | boolean | + /// | char | char | + /// | i8 | byte | + /// | f32 | float | + /// | f64 | double | + /// | i64 | long | + /// | i16 | short | + /// | String | String | + /// | Vec\ | ArrayList\ | + /// | Box\<[u8]\> | byte[] | + /// | [jni::JObject<'env>](jni::objects::JObject) | *(any Java object as input type)* | + /// | [jni::jobject](jni::sys::jobject) | *(any Java object as output)* | + /// |----------------------------------------------------------------------------------------| + #[allow(non_snake_case)] + impl<'env: 'borrow, 'borrow> RustDef<'env, 'borrow> { + //------------------------------------------------------------------------------------------ + // Java methods that can be called from rust + + ///Proof of concept method - shows call from Rust to a java method + /// in order to find the signatures of the class and method, use + /// `javap -s -p file/path/to/compiled/java/class` + /// + /// DO NOT USE THIS METHOD + #[allow(dead_code)] + fn callback(environment: &JNIEnv) -> () { + //This calls a method in Java in the Class RustDef, with the method name "callback" + //and no arguments + environment.call_static_method( + CLASS_SIGNATURE, //Class signature + "callback", //method name signature + "()V", //parameter types of the method + &[], //parameters to be passed to the method + ).expect("Java func call failed"); + } + + /// Creates a new cryptographic key identified by `key_id`. + /// + /// This method generates a new cryptographic key within the TPM. + /// The key is made persistent and associated with the provided `key_id`. + /// + /// # Arguments + /// `key_id` - String that uniquely identifies the key so that it can be retrieved later + /// + /// `key_gen_info` - A string that contains all relevant parameters for the key. Expected format depends on the algorithm: + /// + /// RSA: "KEY_ALGORITHM;KEY_SIZE;HASH;PADDING", + /// + /// EC: "KEY_ALGORITHM;CURVE;HASH" + /// + /// AES + DES: KEY_ALGORITHM;KEY_SIZE;BLOCK_MODE;PADDING" + pub fn create_key(environment: &JNIEnv, key_id: String, key_gen_info: String) -> Result<(), SecurityModuleError> { + RustDef::initialize_module(environment)?; + let result = environment.call_static_method( + CLASS_SIGNATURE, + "create_key", + "(Ljava/lang/String;Ljava/lang/String;)V", + &[JValue::from(environment.new_string(key_id).unwrap()), + JValue::from(environment.new_string(key_gen_info).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(_) => Ok(()), + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::InitializationError( + String::from("Failed to create key: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::InitializationError( + String::from("Failed to create key: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::InitializationError( + String::from("Failed to call Java methods"))), + }; + } + + /// Loads an existing cryptographic key identified by `key_id`. + /// This key can then be used for cryptographic operations such as encryption or signing. + /// + /// # Arguments + /// `key_id` - String that uniquely identifies the key so that it can be retrieved later + pub fn load_key(environment: &JNIEnv, key_id: String) -> Result<(), SecurityModuleError> { + RustDef::initialize_module(environment)?; + let result = environment.call_static_method( + CLASS_SIGNATURE, + "load_key", + "(Ljava/lang/String;)V", + &[JValue::from(environment.new_string(key_id).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(_) => Ok(()), + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::InitializationError( + String::from("Failed to load key: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::InitializationError( + String::from("Failed to load key: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::InitializationError( + String::from("Failed to call Java methods"))), + }; + } + + + /// Initializes the TPM module. + /// + /// This method initializes the TPM context and prepares it for use. It should be called + /// before performing any other operations with the TPM. + /// + /// # Returns + /// + /// A `Result` that, on success, contains `()`, + /// indicating that the module was initialized successfully. + /// On failure, it returns an Error + pub fn initialize_module(environment: &JNIEnv) + -> Result<(), SecurityModuleError> { + let result = environment.call_static_method( + CLASS_SIGNATURE, + "initialize_module", + "()V", + &[], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(_) => Ok(()), + Err(Error::JavaException) => Err(SecurityModuleError::InitializationError( + String::from("Failed to initialise Module: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::InitializationError( + String::from("Failed to call Java methods"))), + }; + } + + /// Signs the given data using the cryptographic key managed by the TPM provider. + /// + /// # Arguments + /// + /// * `data` - A byte slice representing the data to be signed. + /// + /// # Returns + /// + /// A `Result` containing the signature as a `Vec` on success, + /// or an `Error` on failure. + pub fn sign_data(environment: &JNIEnv, data: &[u8]) -> Result, SecurityModuleError> { + let result = environment.call_static_method( + CLASS_SIGNATURE, + "sign_data", + "([B)[B", + &[JValue::from(environment.byte_array_from_slice(data).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(value) => { + let vector = Self::convert_to_Vec_u8(environment, value); + match vector { + Ok(v) => Ok(v), + Err(_) => Err(SecurityModuleError::SigningError( + String::from("Failed to convert return type to rust-compatible format"))), + } + }, + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::SigningError( + String::from("Failed to sign data: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::SigningError( + String::from("Failed to sign data: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::SigningError( + String::from("Failed to call Java methods"))), + }; + } + + /// Verifies the signature of the given data using the key managed by the TPM + /// + /// # Arguments + /// + /// * `data` - A byte slice representing the data whose signature is to be verified + /// * `signature` - A byte slice representing the signature to be verified. + /// + /// # Returns + /// + /// A `Result` containing a `bool` signifying whether the signature is valid, + /// or an `Error` on failure to determine the validity. + pub fn verify_signature(environment: &JNIEnv, data: &[u8], signature: &[u8]) -> Result { + let result = environment.call_static_method( + CLASS_SIGNATURE, + "verify_signature", + "([B[B)Z", + &[JValue::from(environment.byte_array_from_slice(data).unwrap()), + JValue::from(environment.byte_array_from_slice(signature).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(res) => match res.z() { + Ok(value) => Ok(value), + Err(_) => Err(SecurityModuleError::SignatureVerificationError( + String::from("Failed to convert return type to rust-compatible format"))), + }, + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::SignatureVerificationError( + String::from("Failed to verify signature: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::SignatureVerificationError( + String::from("Failed to verify signature: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::SignatureVerificationError( + String::from("Failed to call Java methods"))), + }; + } + + /// Encrypts the given data using the key managed by the TPM + /// + /// # Arguments + /// + /// * `data` - A byte slice representing the data to be encrypted. + /// + /// # Returns + /// + /// A `Result` containing the encrypted data as a `Vec` on success, + /// or an `Error` on failure. + pub fn encrypt_data(environment: &JNIEnv, data: &[u8]) -> Result, SecurityModuleError> { + let result = environment.call_static_method( + CLASS_SIGNATURE, + "encrypt_data", + "([B)[B", + &[JValue::from(environment.byte_array_from_slice(data).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(value) => { + let vector = Self::convert_to_Vec_u8(environment, value); + match vector { + Ok(v) => Ok(v), + Err(_) => Err(SecurityModuleError::EncryptionError( + String::from("Failed to convert return type to rust-compatible format"))), + } + }, + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::EncryptionError( + String::from("Failed to encrypt data: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::EncryptionError( + String::from("Failed to encrypt data: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::EncryptionError( + String::from("Failed to call Java methods"))), + }; + } + + + /// Decrypts the given data using the key managed by the TPM + /// + /// # Arguments + /// + /// * `data` - A byte slice representing the data to be Decrypted. + /// + /// # Returns + /// + /// A `Result` containing the Decrypted data as a `Vec` on success, + /// or an `Error` on failure. + pub fn decrypt_data(environment: &JNIEnv, data: &[u8]) -> Result, SecurityModuleError> { + let result = environment.call_static_method( + CLASS_SIGNATURE, + "decrypt_data", + "([B)[B", + &[JValue::from(environment.byte_array_from_slice(data).unwrap())], + ); + let _ = Self::check_java_exceptions(&environment); + return match result { + Ok(value) => { + let vector = Self::convert_to_Vec_u8(environment, value); + match vector { + Ok(v) => Ok(v), + Err(_) => Err(SecurityModuleError::DecryptionError( + String::from("Failed to convert return type to rust-compatible format"))), + } + }, + Err(Error::WrongJValueType(_, _)) => Err(SecurityModuleError::DecryptionError( + String::from("Failed to decrypt data: Wrong Arguments passed"))), + Err(Error::JavaException) => Err(SecurityModuleError::DecryptionError( + String::from("Failed to decrypt data: Some exception occurred in Java. Check console for details"))), + Err(_) => Err(SecurityModuleError::DecryptionError( + String::from("Failed to call Java methods"))), + }; + } + + //------------------------------------------------------------------------------------------ + // Utility Functions that are only used by other Rust functions. + // These functions have no relation to RustDef.java + + /// Converts a `JValue` representing a Java byte array (`jbyteArray`) to a Rust `Vec`. + /// + /// # Parameters + /// - `environment`: A reference to the JNI environment. This is required for JNI operations. + /// - `result`: The `JValue` that is expected to be a `jbyteArray`. + /// + /// # Returns + /// - `Ok(Vec)` if the conversion is successful. + /// - `Err(String)` if there is an error during the conversion process, with a description of the error. + /// + /// # Errors + /// This method can fail in the following cases: + /// - If there is a pending Java exception. In this case, an appropriate error message is returned. + /// - If the `JValue` cannot be converted to a `Vec`. + /// # Safety + /// Ensure that the `JValue` passed is indeed a `jbyteArray` to avoid undefined behavior or unexpected errors. + fn convert_to_Vec_u8(environment: &JNIEnv, result: JValue) -> Result, String> { + Self::check_java_exceptions(environment)?; + let jobj = result + .l() + .map_err(|_| String::from("Type conversion from JValue to JObject failed"))? + .into_inner() as jbyteArray; + + let output_vec = environment + .convert_byte_array(jobj) + .map_err(|_| String::from("Conversion from jbyteArray to Vec failed"))?; + Self::check_java_exceptions(environment)?; + Ok(output_vec) + } + + /// Checks for any pending Java exceptions in the provided Java environment (`JNIEnv`). + /// If one is detected, it is printed to console and cleared so the program doesn't crash. + /// # Arguments + /// * `environment` - A reference to the Java environment (`JNIEnv`) + /// # Returns + /// * `Result<(), String>` - A Result type representing either success (if no exceptions + /// are found) or an error (if exceptions are found). + /// # Errors + /// This method may return an error of type `JniError` if: + /// * Any pending Java exceptions are found in the provided Java environment. + pub fn check_java_exceptions(environment: &JNIEnv) -> Result<(), String> { + if environment.exception_check().unwrap_or(true) { + let _ = environment.exception_describe(); + let _ = environment.exception_clear(); + return Err(String::from("A Java exception occurred, check console for details")); + } else { + Ok(()) + } + } + } +} \ No newline at end of file diff --git a/src/tpm/android/knox/java/CryptoManager.java b/src/tpm/android/knox/java/CryptoManager.java new file mode 100644 index 00000000..dc634038 --- /dev/null +++ b/src/tpm/android/knox/java/CryptoManager.java @@ -0,0 +1,449 @@ +package tpm.android.knox.java; + +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyInfo; +import android.security.keystore.KeyProperties; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.SignatureException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.InvalidKeySpecException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; + +/** + * This class provides all the methods we need for communication with the keystore and cryptographic systems. + * It loads the keystore, generates and loads keys, encrypts and decrypts and signs and verifies. + * + */ +public class CryptoManager { + private static final String ANDROID_KEY_STORE = "AndroidKeyStore"; + private static final int IV_CBC_AND_CTR_AES = 16; // CBC & CTR standard IV size is 16 Byte + private static final int IV_GCM_AES = 12; // GCM standard IV size is 12 Byte + private static final int IV_CBC_DES = 8; // DES with CBC standard IV size is 8 Byte + private static final int TAG_SIZE_GCM = 128; // 128 is the recommended TagSize + private final KeyStore keyStore; + private String KEY_NAME; + + /** + * Constructs a new instance of {@code CryptoManager} with the default Android KeyStore. + *

    + * This constructor initializes the {@code CryptoManager} with the default Android KeyStore. The Android KeyStore + * provides a secure storage facility for cryptographic keys and certificates. Upon construction, the key store is + * initialized, enabling the {@code CryptoManager} to interact with cryptographic keys securely stored on the + * Android device. If the initialization of the key store fails, a {@link KeyStoreException} is thrown, indicating + * issues with the key store setup process. + * + * @throws KeyStoreException if the KeyStore Provider does not exist or fails to initialize, indicating issues with + * the key store setup process. + */ + public CryptoManager() throws KeyStoreException { + keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); + } + + /** + * Generates a new symmetric key and saves it into the Android KeyStore. + *

    + * This method initializes a new symmetric key for encryption and decryption purposes using the specified symmetric key algorithm. + * The keyGenInfo string is checked for its pattern to ensure that no incorrect values have been transferred. + * The key is stored in the Android KeyStore. + * Additionally, this method ensures that the key is backed by the strong box feature. + * + * @param key_id The unique identifier under which the key will be stored in the KeyStore. + * @param keyGenInfo A string containing key generation parameters separated by semicolons. Expected format: "KEY_ALGORITHM;KEY_SIZE;BLOCK_MODE;PADDING". + * @throws CertificateException if there is an issue loading the certificate chain. + * @throws IOException for I/O errors such as incorrect passwords. + * @throws NoSuchAlgorithmException if the generation algorithm does not exist or the keystore doesn't exist. + * @throws NoSuchProviderException if the provider does not exist. + * @throws InvalidAlgorithmParameterException for invalid or nonexistent parameters. + * @throws KeyStoreException if there is an error accessing the keystore. + */ + public void genKey(String key_id, String keyGenInfo) throws CertificateException, + IOException, NoSuchAlgorithmException, NoSuchProviderException, + InvalidAlgorithmParameterException, KeyStoreException { + Pattern pattern = Pattern.compile("^(AES|DESede);(\\d+);(CBC|GCM|CTR);(NoPadding|PKCS7Padding)$"); + Matcher matcher = pattern.matcher(keyGenInfo); + assert matcher.matches() : "Generate Key keyGenInfo is not valid."; + + String[] keyGenInfoArr = keyGenInfo.split(";"); + String KEY_ALGORITHM = keyGenInfoArr[0]; + int KEY_SIZE = Integer.parseInt(keyGenInfoArr[1]); + String BLOCKING = keyGenInfoArr[2]; + String PADDING = keyGenInfoArr[3]; + + KEY_NAME = key_id; + keyStore.load(null); + + // Check if a key with the given key_id already exists + if (keyStore.containsAlias(KEY_NAME)) { + throw new KeyStoreException("Key with name " + KEY_NAME + " already exists."); + } + KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM, ANDROID_KEY_STORE); + keyGen.init(new KeyGenParameterSpec.Builder(KEY_NAME, + KeyProperties.PURPOSE_ENCRYPT | + KeyProperties.PURPOSE_DECRYPT) + .setKeySize(KEY_SIZE) + .setBlockModes(BLOCKING) + .setEncryptionPaddings(PADDING) + .setIsStrongBoxBacked(true) + .build()); + keyGen.generateKey(); + } + + /** + * Encrypts the given data using a symmetric key stored in the Android KeyStore. + *

    + * This method takes plaintext data as input and encrypts it using a symmetric key retrieved from the Android KeyStore. + * The encryption process supports GCM, CBC and CTR transformations. A new initialization vector (IV) + * is generated and the IV is prepended to the ciphertext. In the case of 3DES only CBC is used, which needs a different IV size than with AES. + * The method initializes a {@link Cipher} instance with the appropriate transformation, loads the Android KeyStore, retrieves the symmetric key, and then + * initializes the cipher in encryption mode with the retrieved key and the generated IV. Finally, the plaintext data is encrypted + * using the cipher's {@code doFinal} method, and the resulting ciphertext is returned as a byte array. + * + * @param data The plaintext data to be encrypted, represented as a byte array. + * @return A byte array representing the encrypted data, with the IV prepended. + * @throws NoSuchPaddingException if the requested padding scheme is not available. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws CertificateException if there is an issue loading the certificate chain. + * @throws IOException if there is an I/O error during the operation. + * @throws InvalidKeyException if the key cannot be cast to a SecretKey. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws IllegalBlockSizeException if the data length is invalid for the encryption algorithm. + * @throws BadPaddingException if the data could not be padded correctly for encryption. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the requested security provider is not available. + */ + public byte[] encryptData(byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, + CertificateException, IOException, InvalidKeyException, UnrecoverableKeyException, + KeyStoreException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, + NoSuchProviderException { + + keyStore.load(null); + SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); + String TRANSFORMATION = buildTransformation(secretKey); + + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + byte[] iv = cipher.getIV(); + if (TRANSFORMATION.contains("/GCM/")) { + assert iv.length == IV_GCM_AES : "AES GCM IV length not matching."; + } else if(TRANSFORMATION.contains("DESede")) { + assert iv.length == IV_CBC_DES : "DES CBC IV length not matching."; + } else { + assert iv.length == IV_CBC_AND_CTR_AES : "AES CBC and CTR IV length not matching."; + } + byte[] encryptedData = cipher.doFinal(data); + ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + encryptedData.length); + byteBuffer.put(iv); + byteBuffer.put(encryptedData); + return byteBuffer.array(); + } + + /** + * Decrypts the given encrypted data using a symmetric key stored in the Android KeyStore. + *

    + * This method takes encrypted data as input and decrypts it using a symmetric key retrieved from the Android KeyStore. + * The decryption process supports GCM, CBC and CTR transformations. The initialization vector (IV) + * is extracted from the beginning of the encrypted data. In the case of 3DES only CBC is used, which needs a different IV size than with AES. + * The method initializes a {@link Cipher} instance with the appropriate + * transformation, loads the Android KeyStore, retrieves the symmetric key, and initializes the cipher in decryption mode with the + * retrieved key and the extracted IV. Finally, the encrypted data is decrypted using the cipher's {@code doFinal} method, and the + * original plaintext data is returned as a byte array. + * + * @param encryptedData The encrypted data to be decrypted, represented as a byte array. + * @return A byte array representing the decrypted data. + * @throws NoSuchPaddingException if the requested padding scheme is not available. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws CertificateException if there is an issue loading the certificate chain. + * @throws IOException if there is an I/O error during the operation. + * @throws InvalidAlgorithmParameterException if the IV parameter is invalid. + * @throws InvalidKeyException if the key cannot be cast to a SecretKey. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws IllegalBlockSizeException if the data length is invalid for the decryption algorithm. + * @throws BadPaddingException if the data could not be padded correctly for decryption. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the requested security provider is not available. + */ + public byte[] decryptData(byte[] encryptedData) throws NoSuchPaddingException, NoSuchAlgorithmException, + CertificateException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, + UnrecoverableKeyException, KeyStoreException, IllegalBlockSizeException, BadPaddingException, + InvalidKeySpecException, NoSuchProviderException { + keyStore.load(null); + SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); + String TRANSFORMATION = buildTransformation(secretKey); + Cipher cipher = Cipher.getInstance(TRANSFORMATION); + ByteBuffer byteBuffer = ByteBuffer.wrap(encryptedData); + byte[] iv; + if (TRANSFORMATION.contains("/GCM/")) { + assert byteBuffer.capacity() > IV_GCM_AES : "Data is not at least IV size in length."; + iv = new byte[IV_GCM_AES]; + byteBuffer.get(iv); + encryptedData = new byte[byteBuffer.remaining()]; + byteBuffer.get(encryptedData); + GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_SIZE_GCM, iv); + cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec); + } else { + if(TRANSFORMATION.contains("DESede")){ + assert byteBuffer.capacity() > IV_CBC_DES : "Data is not at least IV size in length."; + iv = new byte[IV_CBC_DES]; + } + else { + assert byteBuffer.capacity() > IV_CBC_AND_CTR_AES : "Data is not at least IV size in length."; + iv = new byte[IV_CBC_AND_CTR_AES]; + } + byteBuffer.get(iv); + encryptedData = new byte[byteBuffer.remaining()]; + byteBuffer.get(encryptedData); + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); + } + return cipher.doFinal(encryptedData); + } + + /** + * Generates a new asymmetric key pair and saves it into the Android KeyStore. + *

    + * This method generates a new asymmetric key pair suitable for signing and verifying data. + * The key pair is stored in the Android KeyStore. + * The method configures the key pair generator with specific parameters, like the digest algorithms to be supported, + * the signature padding scheme, and whether the key is backed by the strong box feature for enhanced security. + * The generated key pair consists of a private key for signing and a corresponding public key for verification. + * The supported algorithms are RSA and EC. The keyGenInfo string is checked for its pattern to ensure that no incorrect values have been transferred. + * + * @param key_id The unique identifier under which the key pair will be stored in the KeyStore. + * @param keyGenInfo A string containing key generation parameters separated by semicolons. Expected formats: RSA: "KEY_ALGORITHM;KEY_SIZE;HASH;PADDING", EC: "KEY_ALGORITHM;CURVE;HASH". + * @throws CertificateException if there is an issue creating the certificate for the key pair. + * @throws IOException for I/O errors such as incorrect passwords. + * @throws NoSuchAlgorithmException if the generation algorithm does not exist or the keystore doesn't exist. + * @throws InvalidAlgorithmParameterException for invalid or nonexistent parameters. + * @throws NoSuchProviderException if the provider does not exist. + * @throws KeyStoreException if there is an error accessing the keystore or the key name is already used. + */ + public void generateKeyPair(String key_id, String keyGenInfo) throws CertificateException, IOException, + NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, + KeyStoreException { + Pattern pattern = Pattern.compile("^(RSA|EC);(\\d+|secp256r1|secp384r1|secp521r1);(SHA-256)(;PKCS1|;NoPadding)?$"); + Matcher matcher = pattern.matcher(keyGenInfo); + assert matcher.matches() : "Generate KeyPair keyGenInfo is not valid."; + String[] keyGenInfoArr = keyGenInfo.split(";"); + String KEY_ALGORITHM = keyGenInfoArr[0]; + String HASH = keyGenInfoArr[2]; + + KEY_NAME = key_id; + keyStore.load(null); + + // Check if a key with the given key_id already exists + if (keyStore.containsAlias(KEY_NAME)) { + throw new KeyStoreException("Key with name " + KEY_NAME + " already exists."); + } + + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, ANDROID_KEY_STORE); + if (KEY_ALGORITHM.contains("EC")) { + String CURVE = keyGenInfoArr[1]; + keyPairGen.initialize( + new KeyGenParameterSpec.Builder( + KEY_NAME, + KeyProperties.PURPOSE_SIGN) + .setAlgorithmParameterSpec(new ECGenParameterSpec(CURVE)) + .setDigests(HASH) + .build()); + + } else { + int KEY_SIZE = Integer.parseInt(keyGenInfoArr[1]); + String PADDING = keyGenInfoArr[3]; + keyPairGen.initialize(new KeyGenParameterSpec.Builder(KEY_NAME, + KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) + .setKeySize(KEY_SIZE) + .setDigests(HASH) + .setSignaturePaddings(PADDING) + .setIsStrongBoxBacked(true) + .build()); + } + keyPairGen.generateKeyPair(); + } + + /** + * Signs the given data using a private key stored in the Android KeyStore. + *

    + * This method signs the input data with a private key obtained from the Android KeyStore. + * It initializes a {@link Signature} instance with the appropriate algorithm, which is determined dynamically based on the private key's specifications. + * The Android KeyStore is loaded, and the private key associated with a predefined alias is retrieved. + * The signature object is then initialized in sign mode with this private key. + * After updating the signature object with the plaintext data, + * the method completes the signing process by invoking the signature object's {@code sign} method. + * Finally, the method returns the resulting signature as a byte array, which can be used for verification purposes. + * + * @param data The data to be signed, provided as a byte array. + * @return A byte array representing the digital signature of the input data. + * @throws NoSuchAlgorithmException if the requested signature algorithm is not supported. + * @throws UnrecoverableKeyException if the private key cannot be retrieved from the keystore. + * @throws KeyStoreException if there is an issue accessing the keystore. + * @throws InvalidKeyException if the key cannot be cast to a {@link PrivateKey}. + * @throws SignatureException if there is an error during the signing process. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the requested security provider is not available. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + */ + public byte[] signData(byte[] data) throws NoSuchAlgorithmException, UnrecoverableKeyException, + KeyStoreException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchProviderException, CertificateException, IOException { + keyStore.load(null); + Signature signature = Signature.getInstance(buildSignatureAlgorithm((PrivateKey) keyStore.getKey(KEY_NAME, null))); + signature.initSign((PrivateKey) keyStore.getKey(KEY_NAME, null)); + signature.update(data); + return signature.sign(); + } + + /** + * Verifies the given data against a signature produced by a private key stored in the Android KeyStore. + *

    + * This method compares the provided data with the given signature, using the corresponding public key extracted from the Android KeyStore. + * It initializes a {@link Signature} instance with the appropriate algorithm, determined dynamically based on the public key's specifications. + * The method then loads the Android KeyStore, retrieves the public key associated with a predefined alias, + * and initializes the signature object in verify mode with this public key. + * After updating the signature object with the plaintext data, the method verifies the signature against the provided signed bytes + * and returns the result of this verification. + * + * @param data The data that was originally signed, provided as a byte array. + * @param signedBytes The signature produced by signing the original data, provided as a byte array. + * @return {@code true} if the signature matches the data; {@code false} otherwise. + * @throws SignatureException if there is an error during the verification process. + * @throws InvalidKeyException if the key cannot be cast to a {@link PrivateKey}. + * @throws KeyStoreException if there is an issue accessing the keystore. + * @throws NoSuchAlgorithmException if the requested signature algorithm is not supported. + * @throws UnrecoverableKeyException if the public key cannot be retrieved from the keystore. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the requested security provider is not available. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + */ + public boolean verifySignature(byte[] data, byte[] signedBytes) throws SignatureException, InvalidKeyException, + KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException, CertificateException, IOException { + keyStore.load(null); + Signature verificationSignature = Signature.getInstance(buildSignatureAlgorithm((PrivateKey) keyStore.getKey(KEY_NAME, null))); + verificationSignature.initVerify(keyStore.getCertificate(KEY_NAME).getPublicKey()); + verificationSignature.update(data); + return verificationSignature.verify(signedBytes); + } + + /** + * Sets the `KEY_NAME` to the provided key identifier. + *

    + * This method assigns the `KEY_NAME` field with the given `key_id`. + * This is typically used before loading a key with the specified identifier. + * It ensures that the `KEY_NAME` is set correctly for subsequent cryptographic operations + * involving the specified key. + * + * @param key_id The unique identifier of a key to be set as `KEY_NAME`. + * @throws KeyStoreException if there is an issue accessing the keystore. + * @throws UnrecoverableKeyException if the key cannot be retrieved from the keystore. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + */ + public void loadKey(String key_id) throws KeyStoreException, UnrecoverableKeyException, CertificateException, IOException, NoSuchAlgorithmException { + keyStore.load(null); + if (keyStore.containsAlias(key_id)) KEY_NAME = key_id; + else + throw new UnrecoverableKeyException("The key alias '" + key_id + "' does not exist in the KeyStore."); + } + + /** + * Constructs the transformation string for a given key, which is used to initialize a {@link Cipher} instance. + *

    + * This method loads the Android KeyStore and retrieves key-specific metadata using {@link KeyInfo}. + * From those it builds a transformation string based on the key's algorithm, block modes, and padding schemes. The transformation + * string follows the format "algorithm/block-mode/padding". It supports both symmetric keys ({@link SecretKey}) and asymmetric keys + * ({@link PrivateKey}). For symmetric keys, it retrieves encryption paddings; for asymmetric keys, it retrieves signature paddings. + * + * @param key The key for which the transformation string is to be built. It can be either a {@link SecretKey} or a {@link PrivateKey}. + * @return A string representing the transformation in the format "algorithm/mode/padding". + * @throws NullPointerException if the key or any retrieved metadata is null. + * @throws CertificateException if there is an issue with the certificate chain. + * @throws IOException if there is an I/O error during the operation. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the requested security provider is not available. + * @throws KeyStoreException if there is an error accessing the keystore or if the key type is unsupported. + */ + private String buildTransformation(Key key) throws NullPointerException, CertificateException, + IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, KeyStoreException { + keyStore.load(null); + KeyInfo keyInfo; + String keyAlgorithm = key.getAlgorithm(); + String keyPadding; + + if (key instanceof SecretKey) { + SecretKey secretKey = (SecretKey) key; + SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKey.getAlgorithm(), ANDROID_KEY_STORE); + keyInfo = (KeyInfo) factory.getKeySpec(secretKey, KeyInfo.class); + assert(keyInfo.getEncryptionPaddings().length > 0); + keyPadding = keyInfo.getEncryptionPaddings()[0]; + } else if (key instanceof PrivateKey) { + PrivateKey privateKey = (PrivateKey) key; + KeyFactory factory = KeyFactory.getInstance(privateKey.getAlgorithm(), ANDROID_KEY_STORE); + keyInfo = factory.getKeySpec(privateKey, KeyInfo.class); + assert(keyInfo.getSignaturePaddings().length > 0); + keyPadding = keyInfo.getSignaturePaddings()[0]; + } else { + throw new KeyStoreException("Unsupported key type"); + } + assert(keyInfo.getBlockModes().length > 0); + return keyAlgorithm + "/" + keyInfo.getBlockModes()[0] + "/" + keyPadding; + } + + /** + * Constructs the signature algorithm string based on the provided private key. + *

    + * This method retrieves metadata from the given {@link PrivateKey} to dynamically construct + * the signature algorithm string. It uses the {@link KeyFactory} to obtain the {@link KeyInfo} + * of the private key, which includes details such as the digest algorithms supported by the key. + * The method then combines the hash algorithm and the private key algorithm to form the signature + * algorithm string. + *

    + * + * @param privateKey The {@link PrivateKey} for which the signature algorithm string is to be constructed. + * @return A string representing the signature algorithm, which combines the hash algorithm and the key algorithm. + * @throws NoSuchAlgorithmException If the algorithm of the private key is not available. + * @throws NoSuchProviderException If the specified provider is not available. + * @throws InvalidKeySpecException If the key specification is invalid or cannot be retrieved. + */ + private String buildSignatureAlgorithm(PrivateKey privateKey) throws NoSuchAlgorithmException, NoSuchProviderException, + InvalidKeySpecException { + KeyFactory keyFactory = KeyFactory.getInstance(privateKey.getAlgorithm(), ANDROID_KEY_STORE); + KeyInfo keyInfo = keyFactory.getKeySpec(privateKey, KeyInfo.class); + assert(keyInfo.getDigests().length > 0); + String hashAlgorithm = keyInfo.getDigests()[0].replaceAll("-", ""); + String algorithm = privateKey.getAlgorithm(); + if (algorithm.contains("EC")) { + algorithm += "DSA"; + } + return hashAlgorithm + "with" + algorithm; + } + +} \ No newline at end of file diff --git a/src/tpm/android/knox/java/RustDef.java b/src/tpm/android/knox/java/RustDef.java new file mode 100644 index 00000000..a952776b --- /dev/null +++ b/src/tpm/android/knox/java/RustDef.java @@ -0,0 +1,275 @@ +package tpm.android.knox.java; + + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SignatureException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +/** + * This class provides the method declarations that are the interface for the JNI. + * The first part are Rust-methods that can be called from other Java-classes, + * while the second part contains full Java-methods that can be called from Rust. + *

    + * This class also loads the compiled Rust coda as a dynamic library + *

    + * All methods defined in this class hava to have a corresponding method defined in lib.rs, + * with the same method name and corresponding input and output parameters, according to this table: + *

    + * Rust Java + * ------------------------ + * i32 int + * bool boolean + * char char + * i8 byte + * f32 float + * f64 double + * i64 long + * i16 short + * String String + * Vec ArrayList + * Box<[u8]> byte[] + * jni::JObject<'env> (any Java object as input type) + * jni::jobject (any Java object as output) + * + * @noinspection unused - Methods called from Rust are not recognized as being in use + */ +class RustDef { + + /* + CryptoManger object for execution of methods + */ + static CryptoManager cryptoManager; + + static { + // This call loads the dynamic library containing the Rust code. + System.loadLibrary("vulcanslimes"); + } + + //---------------------------------------------------------------------------------------------- + //Rust methods that can be called from Java + + /** + * Proof of concept - shows type conversion + * DO NOT USE + */ + static native ArrayList special(ArrayList input1, int input2); + + + static native String callRust(); + + static native byte[] demoEncrypt(byte[] data); + + static native void demoCreate(String key_id, String key_gen_info); + + static native void demoInit(); + + static native byte[] demoDecrypt(byte[] data); + + static native byte[] demoSign(byte[] data); + + static native boolean demoVerify(byte[] data, byte[] signed_data); + + static native void demoLoad(String key_id); + + //---------------------------------------------------------------------------------------------- + //Java methods that can be called from Rust + + /* + Proof of concept method - get called from Rust when callRust() gets called + DO NOT USE + */ + static void callback() { + System.out.println("Callback successful"); + } + + /** + * Creates a new cryptographic key identified by {@code key_id}. + *

    + * This method generates a new cryptographic key within the TPM. The key is made persistent + * and associated with the provided {@code key_id}, which uniquely identifies the key + * so that it can be retrieved later for cryptographic operations, and {@code keyGenInfo}, + * which holds the information about the key to be generated. + * + * @param key_id a String that uniquely identifies the key to be created within the TPM. + * @param keyGenInfo additional information required for key generation, specifying parameters such as + * key size, algorithm, or other configuration details. + * @throws InvalidAlgorithmParameterException if the specified key generation parameters are invalid or + * incompatible with the key generation process. + * @throws CertificateException if there is an issue with certificate handling, such as failures + * in certificate creation or validation. + * @throws IOException if an I/O error occurs during key generation or processing. + * @throws NoSuchAlgorithmException if the requested cryptographic algorithm for key generation is + * not available or supported. + * @throws KeyStoreException if there is an error accessing the keystore, such as a failure + * to store the newly generated key. + * @throws NoSuchProviderException if the requested security provider is not available or supported. + */ + static void create_key(String key_id, String keyGenInfo) throws InvalidAlgorithmParameterException, CertificateException, + IOException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException { + if (keyGenInfo.contains("RSA") || keyGenInfo.contains("EC")) + cryptoManager.generateKeyPair(key_id, keyGenInfo); + else cryptoManager.genKey(key_id, keyGenInfo); + } + + /** + * Loads an existing cryptographic key identified by {@code key_id}. + *

    + * This method loads an existing cryptographic key from the TPM. The loaded key is + * associated with the provided {@code key_id}, which uniquely identifies the key + * so that it can be retrieved later for cryptographic operations. + * + * @param key_id a String that uniquely identifies the key to be loaded from the TPM. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore, typically due to + * incorrect or inaccessible key information. + * @throws KeyStoreException if there is an error accessing the keystore, such as a failure to load + * or initialize the keystore. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + */ + static void load_key(String key_id) throws UnrecoverableKeyException, KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException { + cryptoManager.loadKey(key_id); + } + + /** + * Initializes the TPM (Trusted Platform Module) module and returns a handle for further operations. + *

    + * This method initializes the TPM context and prepares it for use. It should be called before performing + * any other operations with the TPM. Upon initialization, it sets up the necessary configurations and + * resources required for cryptographic operations involving the TPM. + * + * @throws KeyStoreException if the KeyStore Provider does not exist or fails to initialize, indicating issues + * with the key store setup process. + */ + static void initialize_module() throws KeyStoreException { + cryptoManager = new CryptoManager(); + + } + + /** + * Signs the given data using the key managed by the TPM. + *

    + * This method signs the provided data using the key managed by the TPM (Trusted Platform Module). The data to be + * signed is represented as a byte array. The signing process produces a signature for the data, which is returned as + * a byte array containing the signed data. + * + * @param data a byte array representing the data to be signed. + * @return the signed data as a byte array. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws SignatureException if the signature process encounters an error. + * @throws InvalidKeyException if the key used for signing is invalid. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the provider is not available. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + */ + static byte[] sign_data(byte[] data) throws UnrecoverableKeyException, NoSuchAlgorithmException, + KeyStoreException, SignatureException, InvalidKeyException, InvalidKeySpecException, NoSuchProviderException, CertificateException, IOException { + return cryptoManager.signData(data); + } + + /** + * Verifies the signature of the given data using the key managed by the TPM. + *

    + * This method verifies the signature of the provided data against a known signature using the key managed by the TPM + * (Trusted Platform Module). Both the data and the signature are represented as byte arrays. The verification process + * validates whether the signature matches the data, returning true if the signature is valid and false otherwise. + * + * @param data a byte array representing the data to be verified. + * @param signature a byte array representing the signature to be verified against the data. + * @return true if the signature is valid, false otherwise. + * @throws SignatureException if the signature verification process encounters an error. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws InvalidKeyException if the key used for verification is invalid. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws NoSuchProviderException if the provider is not available. + * @throws CertificateException if there is an error processing certificates. + * @throws IOException if there is an I/O error while interacting with the keystore. + */ + static boolean verify_signature(byte[] data, byte[] signature) throws SignatureException, KeyStoreException, + NoSuchAlgorithmException, InvalidKeyException, UnrecoverableKeyException, InvalidKeySpecException, + NoSuchProviderException, CertificateException, IOException { + return cryptoManager.verifySignature(data, signature); + } + + /** + * Encrypts the given data using the key managed by the TPM. + *

    + * This method encrypts the provided data using the key managed by the TPM (Trusted Platform Module). + * The data to be encrypted is represented as a byte array. The encryption process is performed using cryptographic + * operations managed by the {@link CryptoManager}. The encrypted data is returned as a byte array. + *

    + * This method is called from Rust code, indicating that it may be invoked as part of an integration with a Rust + * application or library. + * + * @param data a byte array representing the data to be encrypted. + * @return a byte array containing the encrypted data. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws NoSuchPaddingException if the padding scheme is not available. + * @throws IllegalBlockSizeException if the block size is invalid for the encryption algorithm. + * @throws CertificateException if there is an issue loading the certificate chain. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws IOException if there is an I/O error during the operation. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws BadPaddingException if the data padding is incorrect for encryption. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws InvalidKeyException if the key is invalid for encryption. + * @throws NoSuchProviderException if the provider is not available. + */ + static byte[] encrypt_data(byte[] data) throws UnrecoverableKeyException, + NoSuchPaddingException, IllegalBlockSizeException, CertificateException, NoSuchAlgorithmException, + IOException, KeyStoreException, BadPaddingException, InvalidKeySpecException, InvalidKeyException, + NoSuchProviderException { + return cryptoManager.encryptData(data); + } + + /** + * Decrypts the given data using the key managed by the TPM. + *

    + * This method decrypts the provided encrypted data using the key managed by the TPM (Trusted Platform Module). + * The encrypted data is represented as a byte array. The decryption process is performed using cryptographic + * operations managed by the {@link CryptoManager}. The decrypted data is returned as a byte array. + *

    + * This method is called from Rust code, indicating that it may be invoked as part of an integration with a Rust + * application or library. + * + * @param encrypted_data a byte array representing the data to be decrypted. + * @return a byte array containing the decrypted data. + * @throws InvalidAlgorithmParameterException if the algorithm parameters are invalid for decryption. + * @throws UnrecoverableKeyException if the key cannot be recovered from the keystore. + * @throws NoSuchPaddingException if the padding scheme is not available. + * @throws IllegalBlockSizeException if the block size is invalid for the decryption algorithm. + * @throws CertificateException if there is an issue loading the certificate chain. + * @throws NoSuchAlgorithmException if the requested algorithm is not available. + * @throws IOException if there is an I/O error during the operation. + * @throws KeyStoreException if there is an error accessing the keystore. + * @throws BadPaddingException if the data padding is incorrect for decryption. + * @throws InvalidKeySpecException if the key specification is invalid. + * @throws InvalidKeyException if the key is invalid for decryption. + * @throws NoSuchProviderException if the provider is not available. + */ + static byte[] decrypt_data(byte[] encrypted_data) throws InvalidAlgorithmParameterException, UnrecoverableKeyException, + NoSuchPaddingException, IllegalBlockSizeException, CertificateException, NoSuchAlgorithmException, + IOException, KeyStoreException, BadPaddingException, InvalidKeySpecException, InvalidKeyException, + NoSuchProviderException { + return cryptoManager.decryptData(encrypted_data); + } +} \ No newline at end of file diff --git a/src/tpm/android/knox/key_handle.rs b/src/tpm/android/knox/key_handle.rs new file mode 100644 index 00000000..05c8f303 --- /dev/null +++ b/src/tpm/android/knox/key_handle.rs @@ -0,0 +1,82 @@ +use tracing::instrument; + +use crate::{ + common::{error::SecurityModuleError, traits::key_handle::KeyHandle}, + tpm::android::knox::interface::jni::RustDef +}; + +use super::KnoxProvider; + +/// Implements the `Provider` trait, providing cryptographic operations +/// such as signing, encryption, decryption, and signature verification for the TPM Knox Vault. +/// +/// This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +/// In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault +impl KeyHandle for KnoxProvider { + /// Signs data using the previously loaded cryptographic key. + /// + /// This method hashes the input data using SHA-256 and then signs the hash. + /// The algorithm used for signing is determined by the currently loaded key. + /// If no key is loaded, an Error is returned. + /// + /// # Arguments + /// + /// * `data` - The data to be signed. + /// + /// # Returns + /// + /// A `Result` containing the signature as a `Vec` on success, or a `SecurityModuleError` on failure. + #[instrument] + fn sign_data(&self, data: &[u8]) -> Result, SecurityModuleError> { + RustDef::sign_data(&self.get_env()?, data) + } + + /// Decrypts the data with the currently loaded key. + /// The algorithm used for decryption is determined by the currently loaded key. + /// If no key is loaded, an Error is returned. + /// # Arguments + /// + /// * `encrypted_data` - The data to be decrypted. + /// + /// # Returns + /// + /// A `Result` containing the decrypted data as a `Vec` on success, or a `SecurityModuleError` on failure. + #[instrument] + fn decrypt_data(&self, encrypted_data: &[u8]) -> Result, SecurityModuleError> { + RustDef::decrypt_data(&self.get_env()?, encrypted_data) + } + + /// Encrypts the data with the currently loaded key. + /// The algorithm used for Encryption is determined by the currently loaded key. + /// If no key is loaded, an Error is returned. + /// # Arguments + /// + /// * `data` - The data to be encrypted. + /// + /// # Returns + /// + /// A `Result` containing the encrypted data as a `Vec` on success, or a `SecurityModuleError` on failure. + #[instrument] + fn encrypt_data(&self, data: &[u8]) -> Result, SecurityModuleError> { + RustDef::encrypt_data(&self.get_env()?, data) + } + + /// Verifies a signature against the provided data. + /// + /// This method hashes the input data using SHA-256 and then verifies the signature with the currently loaded key. + /// The algorithm used for verification is determined by the currently loaded key. + /// If no key is loaded, an Error is returned. + /// # Arguments + /// + /// * `data` - The original data associated with the signature. + /// * `signature` - The signature to be verified. + /// + /// # Returns + /// + /// A `Result` indicating whether the signature is valid (`true`) or not (`false`), + /// or a `SecurityModuleError` on failure. + #[instrument] + fn verify_signature(&self, data: &[u8], signature: &[u8]) -> Result { + RustDef::verify_signature(&self.get_env()?, data, signature) + } +} diff --git a/src/tpm/android/knox/mod.rs b/src/tpm/android/knox/mod.rs index 8b137891..08c14604 100644 --- a/src/tpm/android/knox/mod.rs +++ b/src/tpm/android/knox/mod.rs @@ -1 +1,129 @@ +use std::any::Any; +use std::fmt; +use std::fmt::{Debug, Formatter}; +use robusta_jni::jni::{JavaVM, JNIEnv}; +use tracing::instrument; + +use crate::common::crypto::algorithms::encryption::{AsymmetricEncryption, BlockCiphers}; +use crate::common::traits::module_provider_config::ProviderConfig; +use crate::SecurityModuleError; + +mod interface; +pub mod key_handle; +pub mod provider; + +/// A TPM-based cryptographic provider for managing cryptographic keys and performing +/// cryptographic operations in a Samsung environment. This provider uses the Java Native Interface +/// and the Android Keystore API to access the TPM "Knox Vault" developed by Samsung. In theory, +/// this code should also work for other TPMs on Android Devices, though it is only tested with Knox Vault +#[repr(C)] +pub struct KnoxProvider { + config: Option, +} + +///implements the Debug trait for KnoxProvider to facilitate logging +impl Debug for KnoxProvider { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KnoxProvider") + .field("config", &self.config) + .finish() + } +} + +///Provides functions to manage the KnoxProvider and the stored values within +impl KnoxProvider { + /// Constructs a new `TpmProvider`. + /// + /// # Returns + /// + /// A new empty instance of `TpmProvider`. + #[instrument] + pub fn new() -> Self { + Self { config: None } + } + + /// Sets the configuration for the `Knox` instance. + /// + /// # Arguments + /// + /// * `config` - A `KnoxConfig` instance that contains the configuration settings. + fn set_config(&mut self, config: KnoxConfig) -> () { + self.config = Some(config); + } + + ///Get the JavaVM stored in &self and provides the JNIEnv based on it + /// # Returns + /// + /// a JNIEnv on success to be used for JNI method calls. + /// If the KnoxConfig has not been loaded yet or contains an invalid JavaVM, an error is returned + fn get_env(&self) -> Result { + if self.config.is_none() { return Err(SecurityModuleError::InitializationError(String::from("No key loaded"))); } + let conf = self.config + .as_ref() + .ok_or( + SecurityModuleError::InitializationError(String::from("failed to store config data")))?; + conf.vm + .get_env() + .map_err(|_| SecurityModuleError::InitializationError(String::from("failed to retrieve JNIEnv"))) + } + + ///Converts the config parameter to a KnoxConfig + fn downcast_config(config: Box) -> Result { + Ok(*config + .downcast::() + .map_err(|err| SecurityModuleError::InitializationError(format!("wrong config provided: {:?}", err)))?) + } +} + +/// A struct defining the needed values for the create_key() and load_key() functions +/// At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both. +/// For hashing operations, SHA-256 is always used since it is the only one available on Knox Vault +/// The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI +pub struct KnoxConfig { + pub key_algorithm: Option, + pub sym_algorithm: Option, + pub vm: JavaVM, +} + +/// implements the debug trait for KnoxConfig for logging +impl Debug for KnoxConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("KnoxConfig") + .field("key_algorithm", &self.key_algorithm) + .field("sym_algorithm", &self.sym_algorithm) + .field("JavaVM", &"Contains a JavaVM to interact with Java") + .finish() + } +} + +///implements ProviderConfig for KnoxConfig +impl ProviderConfig for KnoxConfig { + fn as_any(&self) -> &dyn Any { + self + } +} + +/// Implements KnoxConfig and provides a constructor +impl KnoxConfig { + /// creates a new KnoxConfig + /// At any time, either a key_algorithm OR a sym_algorithm must be supplied, not both. + /// Otherwise, load_key() or create_key() will return an Error. + /// The last needed parameter is a JavaVM that is needed to call the Android KeystoreAPI + pub fn new( + key_algorithm: Option, + sym_algorithm: Option, + vm: JavaVM, + ) -> Result { + if (key_algorithm.is_none() && sym_algorithm.is_none()) || + (key_algorithm.is_some() && sym_algorithm.is_some()) { + return Err(SecurityModuleError::InitializationError( + String::from("Either sym_algorithm OR key_algorithm must be Some(_)"))); + } + Ok(Self { + key_algorithm, + sym_algorithm, + vm, + }) + } +} \ No newline at end of file diff --git a/src/tpm/android/knox/provider.rs b/src/tpm/android/knox/provider.rs new file mode 100644 index 00000000..0d80b6ac --- /dev/null +++ b/src/tpm/android/knox/provider.rs @@ -0,0 +1,171 @@ +use std::any::Any; + +use tracing::instrument; + +use crate::{ + common::{ + crypto::algorithms::{ + encryption::{ + AsymmetricEncryption, + BlockCiphers, + EccCurves, + EccSchemeAlgorithm, + SymmetricMode, + }, + KeyBits + }, + error::SecurityModuleError, + traits::module_provider::Provider, + }, + tpm::{ + android::knox::{ + interface::jni::RustDef, + KnoxProvider + }, + core::error::TpmError::UnsupportedOperation + } +}; + +/// Implements the `Provider` trait, providing cryptographic operations utilizing a TPM. +/// +/// This implementation is specific to Samsung Knox Vault and uses the Android Keystore API for all cryptographic operations +/// In theory, this should also work for other TPMs on Android phones, but it is only tested with Samsung Knox Vault +impl Provider for KnoxProvider { + /// Creates a new cryptographic key identified by `key_id`. + /// + /// This method creates a persistent cryptographic key using the specified algorithm + /// and identifier, making it retrievable for future operations. The key is created + /// and stored in Knox Vault. This method also loads the key for further usage, therefore it is + /// not necessary to load a key after creating it. + /// + /// # Arguments + /// + /// * `key_id` - A string slice that uniquely identifies the key to be created. + /// * `Box) -> Result<(), SecurityModuleError> { + let config = Self::downcast_config(config)?; + let sym_alg = config.sym_algorithm; + let asym_alg = config.key_algorithm; + + //Stores the vm for future access + self.set_config(config); + + let key_algo; + if asym_alg.is_some() && sym_alg.is_none() { + key_algo = match asym_alg.expect("Already checked") { + AsymmetricEncryption::Rsa(bitslength) => { + match bitslength { + KeyBits::Bits2048 => { String::from("RSA;2048;SHA-256;PKCS1") } + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported asymmetric encryption algorithm: {:?}", + asym_alg)))); + } + } + } + AsymmetricEncryption::Ecc(scheme) => { + match scheme { + EccSchemeAlgorithm::EcDsa(curve) => { + match curve { + EccCurves::P256 => { String::from("EC;secp256r1;SHA-256") } + EccCurves::P384 => { String::from("EC;secp384r1;SHA-256") } + EccCurves::P521 => { String::from("EC;secp521r1;SHA-256") } + // EccCurves::Curve25519 => { String::from("EC;X25519;SHA-256") } <- x25519 may ONLY be used for key agreement, not signing + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported asymmetric encryption algorithm: {:?}", + asym_alg)))); + } + } + } + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported asymmetric encryption algorithm: {:?}", + asym_alg)))); + } + } + } + }; + } else if asym_alg.is_none() && sym_alg.is_some() { + key_algo = match sym_alg.expect("Already checked") { + BlockCiphers::Des => { String::from("DESede;168;CBC;PKCS7Padding") } + + BlockCiphers::Aes(block, bitslength) => { + let mut rv = String::from("AES;"); + match bitslength { + KeyBits::Bits128 => { rv += "128;"; } + KeyBits::Bits192 => { rv += "192;"; } + KeyBits::Bits256 => { rv += "256;"; } + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg)))); + } + } + match block { + SymmetricMode::Gcm => { rv += "GCM;NoPadding" } + SymmetricMode::Cbc => { rv += "CBC;PKCS7Padding" } + SymmetricMode::Ctr => { rv += "CTR;NoPadding" } + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg)))); + } + } + rv + } + _ => { + return Err(SecurityModuleError::Tpm(UnsupportedOperation( + format!("Unsupported symmetric encryption algorithm: {:?}", sym_alg)))); + } + }; + } else { + return Err(SecurityModuleError::CreationError(format!( + "wrong parameters in KnoxConfig: + Exactly one of either sym_algorithm or key_algorithm must be Some().\ + sym_algorithm: {:?}\ + key_algorithm: {:?}", + sym_alg, + asym_alg))); + } + RustDef::create_key(&self.get_env()?, String::from(key_id), key_algo) + } + + /// Loads an existing cryptographic key identified by `key_id`. + /// + /// This method attempts to load a persisted cryptographic key by its identifier from the TPM. + /// If successful, it enables the key to be used for cryptographic operations. + /// + /// # Arguments + /// + /// * `key_id` - A string slice that uniquely identifies the key to be loaded. + /// * `Box) -> Result<(), SecurityModuleError> { + //Stores the vm for future access + let config = Self::downcast_config(config)?; + self.set_config(config); + + RustDef::load_key(&self.get_env()?, key_id.to_string()) + } + + ///This function ordinarily initialises the HSM. + /// For our implementation, this is not needed. You do not need to call this method, + /// and it will always return Ok(()) if you do. + fn initialize_module(&mut self) -> Result<(), SecurityModuleError> { + Ok(()) + } +} diff --git a/src/tpm/core/instance.rs b/src/tpm/core/instance.rs index 6f49b4e3..fb88046e 100644 --- a/src/tpm/core/instance.rs +++ b/src/tpm/core/instance.rs @@ -129,7 +129,9 @@ impl TpmInstance { AndroidTpmType::Keystore => Arc::new(Mutex::new( crate::tpm::android::AndroidProvider::new(key_id), )), - AndroidTpmType::Knox => todo!(), + AndroidTpmType::Knox => Arc::new(Mutex::new( + crate::tpm::android::knox::KnoxProvider::new(), + )), }, TpmType::None => todo!(), }