pjs.decrypt()

pjs.decrypt()

This API was added in Profound.js / Profound API version 7.

Description

pjs.decrypt() decrypts data that was encrypted with pjs.encrypt() and returns the original data. The whole value is decrypted in a single operation from data already loaded into memory.

The encryption algorithm is AES-256-GCM. Because that algorithm is authenticated, decryption is also a verification step: if the wrong key is used, or if even one byte of the encrypted value has changed, the call throws instead of returning altered data. See Encryption API for the layout of the encrypted value.

Syntax

pjs.decrypt(data) pjs.decrypt(data, key)

Parameters

  1. Data (Buffer) - The encrypted data to decrypt, exactly as it was returned by pjs.encrypt(). Must be a Node.js Buffer object and must be at least 28 bytes long. If the value was stored as Base64 or hex, convert it back to a Buffer first.

  2. Encryption key (Buffer, optional) - The key the data was encrypted with. If passed, it must be a Buffer of exactly 32 bytes. If it is not passed, the key from the encryptionKey configuration setting is used.

To use the configured key, leave the second parameter off entirely. Passing undefined or null explicitly still counts as supplying the parameter, and the call fails with "key" argument must be a Buffer. rather than falling back to the encryptionKey setting.

Return Value

A Buffer object containing the decrypted data. It is exactly 28 bytes shorter than the encrypted Buffer that was passed in. Convert it back to its original form with .toString() for text, or use the Buffer directly for binary content.

Exception Handling

The call throws an Error instead of returning a value in the following cases. The key is validated first, then the data type, then the data length, and finally the contents.

  • No key available - The second parameter was omitted and no encryptionKey setting is configured. The message begins with This feature requires an encryption key.

  • Key is not a Buffer - A second parameter was supplied but is not a Buffer. The message is "key" argument must be a Buffer.

  • Key is the wrong size - A Buffer was supplied but is not exactly 32 bytes. The message is "key" argument must be 32 bytes.

  • Data is not a Buffer - The message is "data" argument must be a Buffer.

  • Data is too short - The Buffer is shorter than 28 bytes, so it cannot hold an initialization vector and an authentication tag and was not produced by pjs.encrypt(). The message is Invalid data format.

  • Wrong key or altered data - The Buffer is the right shape but fails authentication, because the key does not match, the value was modified, or bytes were lost in storage or transport. Node.js reports this as Unsupported state or unable to authenticate data.

The last case is the one worth handling in application code. It cannot be distinguished from a wrong-key error by the message alone, so treat it as “this value could not be trusted” rather than trying to determine the exact cause. A frequent source of it is a round trip through a character column or an interface that trimmed, padded, or re-encoded the bytes – see Example 2 below.

Examples

Example 1: Decrypt a Value Stored as Base64

This is the counterpart to the common storage pattern: an encrypted value was Base64-encoded so it could be held in a character column, and is now being read back.

Prerequisite: the value was produced by pjs.encrypt() using the key that is currently configured in the encryptionKey setting.

// The Base64 string exactly as it was read out of the database column, // with no trimming or re-encoding. A 16-byte account number encrypts to // 44 bytes, which is 60 Base64 characters. const stored = customerRecord.ACCTENC; // Convert back to the exact bytes pjs.encrypt() produced. Skipping this // step passes a string, which fails with '"data" argument must be a Buffer.' const encrypted = Buffer.from(stored, "base64"); // Decrypt with the configured key, then convert the Buffer back to text. const accountNo = pjs.decrypt(encrypted).toString(); return accountNo;

Example 2: Handle a Failed Decryption

Decryption failures are normal to plan for: a key was rotated, a record was copied from another environment, or a character column silently trimmed trailing blanks. Wrap the call so a bad value produces a clear message instead of an unhandled error, and never report the underlying text to an end user.

Prerequisite: none. This pattern works with either key source.

function readSecret(base64Value) { const encrypted = Buffer.from(base64Value, "base64"); // A value that is not at least 28 bytes was never produced by // pjs.encrypt(), so report that separately from a key mismatch. if (encrypted.length < 28) { console.error("Stored value is too short to be encrypted data."); return null; } try { return pjs.decrypt(encrypted).toString(); } catch (error) { // Reached when the key does not match or the bytes were altered. // Log the detail for support; return a neutral result to the caller. console.error("Unable to decrypt stored value: " + error.message); return null; } } return readSecret(storedValue);

Example 3: Decrypt a File on the IFS

The counterpart to encrypting a file. Read and write in binary throughout – passing an encoding to readFileSync() returns a string and the call fails on the data type check.

Prerequisite: the encrypted file was written by pjs.encrypt() and has not been edited or transferred in text mode.

const fs = require("fs"); // No encoding argument, so readFileSync() returns raw bytes. const encryptedFile = fs.readFileSync("/home/payroll/export.csv.enc"); // Decrypt with the configured key. Throws if the file was altered, // which is exactly the check you want before trusting its contents. const plainFile = pjs.decrypt(encryptedFile); // Write the recovered file, or work with the Buffer directly to avoid // leaving a plain text copy on the IFS. fs.writeFileSync("/home/payroll/export.csv", plainFile); return plainFile.toString().split("\n").length; // line count

Requirements

An encryption key must be available, either as the second parameter or through the encryptionKey configuration setting, and it must be the same key the data was encrypted with.


Related Pages