The example goes through the following steps:
-
require
all the necessary modules:crypto
, the test subject;fs
, read and write simple text files;path
, resolve file paths;assert
, test the result of the operations;
-
setup some utility objects and the cryptography-related functions, including a key that goes through SHA256 (AES-256 requires 256 bits of key (32 Bytes)); Note: Differently from example1, the encrypt function now appends the encrypted content after the IV buffer (which is not encrypted in any way).
-
if the encrypted file is missing, a generation function creates it with following rules:
-
read synchronously the encrypted text file from disk and store it in memory (utf8 encoding);
-
from the read encrypted file extract the first 16 bytes since they are the IV used during the encryption process;
-
from the read encrypted file extract everything past the first 16 bytes as it is the actual encrypted content;
-
decrypt the encrypted content using the extracted IV and the provided secret (fixed);
-
simple test using Node's integrated assert function (match between plain text and decrypted content).
There are in a few occasions unnecessary convertions from Buffer
instances to string
instances. They are there for convenience purposes (debug) since the crypto
module's functions transform strings into buffers internally anyway.