Member Junction
    Preparing search index...

    Core encryption engine for field-level encryption operations.

    This class uses composition to delegate metadata operations to EncryptionEngineBase while adding encryption/decryption capabilities. This avoids duplicate entity registration that occurred when using inheritance.

    Use EncryptionEngine.Instance to access the singleton.

    The engine is designed to be safe for concurrent use in async contexts. Cache operations are atomic Map operations and crypto operations use per-call state.

    The engine throws descriptive errors for:

    • Missing keys or configurations
    • Invalid encrypted value format
    • Decryption failures (including auth tag mismatch)
    • Key length mismatches

    Callers should catch and handle errors appropriately.

    Hierarchy (View Summary)

    Index

    Constructors

    Accessors

    • get Instance(): EncryptionEngine

      Gets the singleton instance of the encryption engine.

      The instance is created on first access and reused thereafter.

      Returns EncryptionEngine

      const engine = EncryptionEngine.Instance;
      await engine.Config(false, contextUser);
      const encrypted = await engine.Encrypt(data, keyId, contextUser);

    Methods

    • Clears all caches including base class metadata caches.

      This is more aggressive than ClearCaches() and should be used when you need to completely refresh all cached data.

      Returns Promise<void>

    • Clears key material and source caches.

      Call after key rotation or configuration changes to ensure fresh data is loaded. The base class metadata caches are handled separately via RefreshAllItems().

      Key material buffers are explicitly zeroed before removal to minimize the window where sensitive bytes linger in memory.

      Returns void

    • Configures the engine by loading encryption metadata from the database.

      Delegates to EncryptionEngineBase to load metadata. Must be called before performing encryption/decryption operations.

      Parameters

      • OptionalforceRefresh: boolean

        If true, reloads data even if already loaded

      • OptionalcontextUser: UserInfo

        User context for database access (required server-side)

      • Optionalprovider: IMetadataProvider

        Optional metadata provider override

      Returns Promise<void>

    • Decrypts an encrypted value.

      If the value is not encrypted (doesn't start with marker), returns it unchanged.

      The method:

      1. Parses the encrypted value to extract key ID and parameters
      2. Gets the key configuration from cached metadata
      3. Retrieves key material from the configured source (cached)
      4. Decrypts using the algorithm and IV from the encrypted value
      5. Verifies the auth tag for AEAD algorithms

      Parameters

      • value: string

        The value to decrypt (may or may not be encrypted)

      • OptionalcontextUser: UserInfo

        User context for database access

      Returns Promise<string>

      The decrypted plaintext, or original value if not encrypted

      Error if decryption fails (invalid key, corrupted data, auth tag mismatch)

      // Decrypt an encrypted value
      const plaintext = await engine.Decrypt(encryptedValue, contextUser);

      // Non-encrypted values pass through unchanged
      const same = await engine.Decrypt('plain-text', contextUser);
      // Returns: 'plain-text'
    • Encrypts a value using the specified encryption key.

      The method:

      1. Gets the key configuration from cached metadata
      2. Retrieves key material from the configured source (cached)
      3. Generates a random IV
      4. Encrypts the data using the configured algorithm
      5. Returns a self-describing encrypted string

      The result format is: $ENC$<keyId>$<algorithm>$<iv>$<ciphertext>[$<authTag>]

      This format contains all information needed for decryption.

      Parameters

      • plaintext: string | Buffer

        The value to encrypt (string or Buffer)

      • encryptionKeyId: string

        UUID of the encryption key to use

      • OptionalcontextUser: UserInfo

        User context for database access

      Returns Promise<string>

      The encrypted value as a string

      Error if the key cannot be found or is invalid

      Error if key material retrieval fails

      const encrypted = await engine.Encrypt(
      'secret-api-key',
      '550e8400-e29b-41d4-a716-446655440000',
      currentUser
      );
      // Returns: $ENC$550e8400-....$AES-256-GCM$<iv>$<ciphertext>$<authTag>
    • Encrypts a value using a specific key lookup (for key rotation).

      During key rotation, we need to encrypt with the new key material before updating the key metadata. This method allows specifying an alternate lookup value for the key material.

      Parameters

      • plaintext: string | Buffer

        The value to encrypt

      • encryptionKeyId: string

        The key ID (for algorithm/marker config)

      • keyLookupValue: string

        Alternate lookup value for key material

      • OptionalcontextUser: UserInfo

        User context for database access

      Returns Promise<string>

      The encrypted value string

    • The Global Object Store is a place to store global objects that need to be shared across the application. Depending on the execution environment, this could be the window object in a browser, or the global object in a node environment, or something else in other contexts. The key here is that in some cases static variables are not truly shared because it is possible that a given class might have copies of its code in multiple paths in a deployed application. This approach ensures that no matter how many code copies might exist, there is only one instance of the object in question by using the Global Object Store.

      Returns GlobalObjectStore

    • Checks if a value is encrypted.

      Encrypted values start with the marker prefix (default: '$ENC$'). This also checks for the encrypted sentinel value. This is a fast, synchronous check that doesn't require database access.

      Parameters

      • value: unknown

        The value to check

      • OptionalencryptionMarker: string

        Optional custom marker to check for (defaults to '$ENC$')

      Returns boolean

      true if the value appears to be encrypted or is the sentinel value

    • Parses an encrypted value string into its component parts.

      Use this when you need to inspect the encrypted value without decrypting.

      Parameters

      • value: string

        The encrypted value string

      Returns EncryptedValueParts

      Parsed components (marker, keyId, algorithm, iv, ciphertext, authTag)

      Error if the format is invalid

    • Validates that ALL active encryption keys have accessible key material.

      This method iterates through every active encryption key in the system, instantiates the appropriate key source provider, and delegates validation to each provider's ValidateKeyAccessibility() method. Each provider encapsulates its own validation logic and generates source-specific error messages with actionable remediation steps.

      The engine never touches key material during validation — that stays encapsulated within each provider.

      Parameters

      • OptionalcontextUser: UserInfo

        User context for database access

      Returns Promise<
          {
              Error?: string;
              IsAccessible: boolean;
              KeyId: string;
              KeyName: string;
              LookupValue: string;
              SourceType: string;
          }[],
      >

      Array of validation results, one per active key

    • Validates that a key is usable for encryption operations.

      Parameters

      • keyId: string

      Returns { error?: string; isValid: boolean }

    • Validates that key material is accessible at a given lookup value.

      Used before key rotation to verify the new key exists and is valid.

      Parameters

      • lookupValue: string

        The key source lookup value to validate

      • encryptionKeyId: string

        The key ID (to get source configuration)

      • OptionalcontextUser: UserInfo

        User context for database access

      Returns Promise<void>

      Error if the key material cannot be accessed or is invalid

    • Returns the singleton instance of the class. If the instance does not exist, it is created and stored in the Global Object Store. If className is provided it will be used as part of the key in the Global Object Store, otherwise the actual class name will be used. NOTE: the class name used by default is the lowest level of the object hierarchy, so if you have a class that extends another class, the lowest level class name will be used.

      Type Parameters

      Parameters

      • this: new () => T
      • OptionalclassName: string

      Returns T