# Rhai Scripting for WebAssembly Cryptography Module This directory contains example Rhai scripts that demonstrate how to use the WebAssembly Cryptography Module's scripting capabilities. ## Key Space Persistence The Rhai API now supports key space persistence, allowing you to create key spaces and keypairs in one script and use them in another. This is achieved through the following functions: ### Key Space Management Functions - `load_key_space(name, password)`: Loads a key space from disk by name and decrypts it with the provided password. - `create_key_space(name, password)`: Creates a new key space with the given name and automatically saves it to disk encrypted with the provided password. - `encrypt_key_space(password)`: Encrypts the current key space and returns the encrypted data as a string. - `decrypt_key_space(encrypted_data, password)`: Decrypts an encrypted key space and sets it as the current key space. ### Example Usage ```rhai // Create a key space (automatically saves to disk) let space_name = "my_space"; let password = "secure_password"; if create_key_space(space_name, password) { // Create keypairs (automatically saves to disk) create_keypair("my_keypair", password); } // Later, in another script: if load_key_space(space_name, password) { // Use the keypair select_keypair("my_keypair"); let signature = sign("Hello, world!"); } ``` ## Example Scripts 1. **example.rhai**: Basic example demonstrating key management, signing, and encryption. 2. **advanced_example.rhai**: Advanced example with error handling and more complex operations. 3. **key_persistence_example.rhai**: Demonstrates creating and saving a key space to disk. 4. **load_existing_space.rhai**: Shows how to load a previously created key space and use its keypairs. ## Key Space Storage Key spaces are stored in the `~/.hero-vault/key-spaces/` directory by default. Each key space is stored in a separate JSON file named after the key space (e.g., `my_space.json`). ## Security Key spaces are encrypted with ChaCha20Poly1305 using a key derived from the provided password. The encryption ensures that the key material is secure at rest. ## Best Practices 1. **Use Strong Passwords**: Since the security of your key spaces depends on the strength of your passwords, use strong, unique passwords. 2. **Backup Key Spaces**: Regularly backup your key spaces directory to prevent data loss. 3. **Script Organization**: Split your scripts into logical units, with separate scripts for key creation and key usage. 4. **Error Handling**: Always check the return values of functions to ensure operations succeeded before proceeding.