### Create Encryption Instances for Tests with EncryptionFactory Source: https://context7.com/adonisjs/encryption/llms.txt A factory class for creating `Encryption` instances specifically for tests. It allows for pre-configured defaults and customization of encryption options, simplifying test setup. ```typescript import { EncryptionFactory } from '@adonisjs/encryption/factories' // Create encryption instance with default test secret const encryption = new EncryptionFactory().create() // Customize options for specific test scenarios const customEncryption = new EncryptionFactory() .merge({ secret: 'custom-test-secret-key' }) .create() // Use in tests const encrypted = encryption.encrypt({ userId: 1 }) const decrypted = encryption.decrypt(encrypted) // Output: { userId: 1 } ``` -------------------------------- ### Base64 Utilities Source: https://context7.com/adonisjs/encryption/llms.txt Utilities for URL-safe base64 encoding and decoding. ```APIDOC ## POST /base64/urlEncode ### Description Performs URL-safe base64 encoding on the provided input. ### Method POST ### Endpoint /base64/urlEncode ### Parameters #### Query Parameters - **input** (string | Buffer) - Required - The data to encode. ### Request Example ```json { "input": "Hello World!" } ``` ### Response #### Success Response (200) - **encoded** (string) - The URL-safe base64 encoded string. #### Response Example ```json { "encoded": "SGVsbG8gV29ybGQh" } ``` ## POST /base64/urlDecode ### Description Performs URL-safe base64 decoding on the provided input. ### Method POST ### Endpoint /base64/urlDecode ### Parameters #### Query Parameters - **input** (string) - Required - The URL-safe base64 encoded string to decode. ### Request Example ```json { "input": "SGVsbG8gV29ybGQh" } ``` ### Response #### Success Response (200) - **decoded** (string) - The decoded string. #### Response Example ```json { "decoded": "Hello World!" } ``` ``` -------------------------------- ### Handle Encryption Errors: Missing or Insecure App Key Source: https://context7.com/adonisjs/encryption/llms.txt Demonstrates how the AdonisJS Encryption package throws specific errors for invalid secret configurations. It covers `E_MISSING_APP_KEY` for a missing secret and `E_INSECURE_APP_KEY` for a secret that is too short. ```typescript import { Encryption, errors } from '@adonisjs/encryption' // Missing secret throws E_MISSING_APP_KEY try { new Encryption({ secret: null as any }) } catch (error) { console.log(error.code) // 'E_MISSING_APP_KEY' console.log(error.message) // 'Missing "app.appKey". The key is required to encrypt values' } // Short secret throws E_INSECURE_APP_KEY try { new Encryption({ secret: 'short' }) } catch (error) { console.log(error.code) // 'E_INSECURE_APP_KEY' console.log(error.message) // 'The value of "app.appKey" should be atleast 16 characters long' } ``` -------------------------------- ### EncryptionFactory (Testing) Source: https://context7.com/adonisjs/encryption/llms.txt Factory for creating Encryption instances specifically for testing purposes. ```APIDOC ## POST /encryption/factory/create ### Description Creates an Encryption instance using a factory, suitable for testing environments. Allows for default or custom configuration. ### Method POST ### Endpoint /encryption/factory/create ### Parameters #### Query Parameters - **options** (object) - Optional - Configuration options to merge with defaults (e.g., `{ secret: 'custom-test-secret-key' }`). ### Request Example ```json { "options": {"secret": "custom-test-secret-key"} } ``` ### Response #### Success Response (200) - **encryptionInstance** (object) - An instance of the Encryption class configured for testing. #### Response Example ```json { "encryptionInstance": "[Encryption Instance Object]" } ``` ``` -------------------------------- ### Create Encryption Instance with Secret Key Source: https://context7.com/adonisjs/encryption/llms.txt Initializes the Encryption class with a required secret key. The secret must be at least 16 characters long for security. An alternative initialization uses the `Secret` wrapper from `@poppinss/utils` for more secure memory handling. ```typescript import { Encryption } from '@adonisjs/encryption' // Basic initialization with secret key const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // Using Secret wrapper for secure memory handling import { Secret } from '@poppinss/utils' const secureEncryption = new Encryption({ secret: new Secret('averylongrandom32charactersstring') }) ``` -------------------------------- ### Error Handling Source: https://context7.com/adonisjs/encryption/llms.txt Details on specific errors thrown by the Encryption component related to secret configuration. ```APIDOC ## Error Codes ### E_MISSING_APP_KEY #### Description Thrown when the encryption secret (`app.appKey`) is not provided during Encryption instance creation. ### E_INSECURE_APP_KEY #### Description Thrown when the provided encryption secret is less than 16 characters long, indicating an insecure key. ``` -------------------------------- ### Create Child Encryption Instance with Different Secret Source: https://context7.com/adonisjs/encryption/llms.txt Generates a new `Encryption` instance with potentially different configuration, such as a distinct secret key. This is useful for isolating encryption contexts within the same application. Values encrypted with one instance cannot be decrypted by another instance using a different secret. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // Create child instance with different secret const customEncryption = encryption.child({ secret: 'another-secret-key-here' }) // Values encrypted with different secrets cannot be decrypted by each other const encrypted = customEncryption.encrypt('hello-world') const result = encryption.decrypt(encrypted) // Output: null (different secrets) // Child instance can decrypt its own values const childDecrypted = customEncryption.decrypt(encrypted) // Output: 'hello-world' ``` -------------------------------- ### URL-Safe Base64 Encoding and Decoding with AdonisJS Encryption Source: https://context7.com/adonisjs/encryption/llms.txt Provides URL-safe base64 encoding and decoding utilities through the `Encryption` class. This is useful for handling binary data or strings that need to be safely transmitted in URLs. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // URL-safe base64 encoding const encoded = encryption.base64.urlEncode('Hello World!') // Output: "SGVsbG8gV29ybGQh" // URL-safe base64 decoding const decoded = encryption.base64.urlDecode(encoded) // Output: "Hello World!" // Binary data encoding const buffer = Buffer.from([0x00, 0x01, 0x02, 0x03]) const binaryEncoded = encryption.base64.urlEncode(buffer) ``` -------------------------------- ### Sign and Unsign Payload Source: https://context7.com/adonisjs/encryption/llms.txt API endpoints for signing payloads with HMAC-SHA256 for integrity verification and unsigning to extract the original value. ```APIDOC ## POST /verifier/sign ### Description Signs a value without encryption using HMAC-SHA256, creating a base64-encoded payload with integrity verification. The original data remains visible but tamper-proof. ### Method POST ### Endpoint /verifier/sign ### Parameters #### Query Parameters - **payload** (object | string | null | undefined) - Required - The value to sign. - **expiresIn** (string) - Optional - The expiration time for the signature (e.g., '24h'). - **purpose** (string) - Optional - A string to associate with the signature for specific use cases. ### Request Example ```json { "payload": {"username": "virk"} } ``` ### Response #### Success Response (200) - **signedPayload** (string) - The base64-encoded signed payload. #### Response Example ```json { "signedPayload": "eyJtZXNzYWdlIjp7InVzZXJuYW1lIjoidmlyayJ9fQ.aG1hYy1zaWduYXR1cmU" } ``` ## POST /verifier/unsign ### Description Verifies and extracts the original value from a signed payload. Returns `null` if the signature is invalid, tampered, or the purpose doesn't match. ### Method POST ### Endpoint /verifier/unsign ### Parameters #### Query Parameters - **payload** (string) - Required - The signed payload to verify. - **purpose** (string) - Optional - The expected purpose associated with the signature. ### Request Example ```json { "payload": "eyJtZXNzYWdlIjp7InVzZXJuYW1lIjoidmlyayJ9fQ.aG1hYy1zaWduYXR1cmU", "purpose": "password-reset" } ``` ### Response #### Success Response (200) - **unsignedPayload** (object | string | null) - The original, unsigned payload, or null if verification fails. #### Response Example ```json { "unsignedPayload": {"userId": 123} } ``` ``` -------------------------------- ### Unsign Data and Verify Signature with AdonisJS Encryption Source: https://context7.com/adonisjs/encryption/llms.txt Verifies and extracts the original value from a signed payload. Returns `null` if the signature is invalid, tampered, or the purpose doesn't match. Handles basic unsigning, purpose verification, and detects tampered or invalid formats. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) const verifier = encryption.verifier // Basic unsign const signed = verifier.sign({ username: 'virk' }) const unsigned = verifier.unsign(signed) // Output: { username: 'virk' } // Unsign with purpose verification const resetToken = verifier.sign({ userId: 123 }, undefined, 'password-reset') const validUnsign = verifier.unsign(resetToken, 'password-reset') // Output: { userId: 123 } const invalidUnsign = verifier.unsign(resetToken, 'login') // Output: null (purpose mismatch) // Tampered values return null const tampered = signed.slice(0, -2) verifier.unsign(tampered) // Output: null // Invalid formats return null verifier.unsign('helloworld') // null (missing separator) verifier.unsign('hello.world') // null (unable to decode) ``` -------------------------------- ### Encrypt Payload with Expiration and Purpose Source: https://context7.com/adonisjs/encryption/llms.txt Encrypts serializable data using AES-256-CBC with a unique IV. The output is a base64-encoded string. Supports optional expiration times (e.g., '1h', '30m') and purpose strings for context-specific verification. Identical payloads produce different encrypted outputs due to random IV generation. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // Encrypt a string const encryptedString = encryption.encrypt('hello-world') // Output: "dGVzdC1lbmNyeXB0ZWQ.aXYtdmFsdWU.aG1hYy1oYXNo" // Encrypt an object const encryptedObject = encryption.encrypt({ username: 'virk', role: 'admin' }) // Encrypt with expiration (1 hour) const expiringToken = encryption.encrypt({ userId: 123 }, '1h') // Encrypt with purpose for context-specific decryption const loginToken = encryption.encrypt({ userId: 123 }, '30m', 'login') // Each encryption produces unique output due to random IV const first = encryption.encrypt({ username: 'virk' }) const second = encryption.encrypt({ username: 'virk' }) console.log(first === second) // false ``` -------------------------------- ### Decrypt Encrypted Value with Purpose Verification Source: https://context7.com/adonisjs/encryption/llms.txt Decrypts a base64-encoded string, verifying its integrity using HMAC and optionally checking the purpose. Returns the original data if successful, or `null` if decryption fails, the value is tampered with, has expired, or the purpose does not match. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // Basic decryption const encrypted = encryption.encrypt({ username: 'virk' }) const decrypted = encryption.decrypt(encrypted) // Output: { username: 'virk' } // Decryption with purpose verification const loginToken = encryption.encrypt({ userId: 123 }, undefined, 'login') const validDecrypt = encryption.decrypt(loginToken, 'login') // Output: { userId: 123 } const invalidDecrypt = encryption.decrypt(loginToken, 'register') // Output: null (purpose mismatch) // Tampered values return null const tampered = encrypted.slice(2) // Remove first 2 characters const result = encryption.decrypt(tampered) // Output: null // Invalid format returns null encryption.decrypt('invalid-string') // null encryption.decrypt(null) // null encryption.decrypt('foo.bar.baz') // null (unable to decode) ``` -------------------------------- ### Sign Data with HMAC-SHA256 using AdonisJS Encryption Source: https://context7.com/adonisjs/encryption/llms.txt Signs a value without encryption using HMAC-SHA256, creating a base64-encoded payload with integrity verification. The original data remains visible but tamper-proof. Supports optional expiration times and purposes. ```typescript import { Encryption } from '@adonisjs/encryption' const encryption = new Encryption({ secret: 'averylongrandom32charactersstring' }) // Access verifier through encryption instance const verifier = encryption.verifier // Sign an object const signed = verifier.sign({ username: 'virk' }) // Output: "eyJtZXNzYWdlIjp7InVzZXJuYW1lIjoidmlyayJ9fQ.aG1hYy1zaWduYXR1cmU" // Sign with expiration const expiringSignature = verifier.sign({ sessionId: 'abc123' }, '24h') // Sign with purpose const purposedSignature = verifier.sign({ userId: 123 }, undefined, 'password-reset') // Note: null and undefined cannot be signed try { verifier.sign(null) // Throws: Cannot sign "null" value } catch (error) { console.error(error.message) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.