Detailed Walkthrough of AES Encryption and Decryption Process with Node.js Implementation

This article provides a step‑by‑step technical guide to the AES encryption and decryption algorithm, covering state matrix construction, key expansion, round operations, final round differences, and practical Node.js code examples for handling padding and common implementation pitfalls.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Detailed Walkthrough of AES Encryption and Decryption Process with Node.js Implementation

The article introduces AES by suggesting the reader prepare coffee, paper, and a pen before diving into a thorough explanation of the algorithm’s encryption and decryption steps.

Data is first placed into a 4×4 "state matrix" and padded at the end if the plaintext does not exactly fill 16 bytes.

In the initial round the state matrix is XOR‑ed with the first round key, a fast low‑cost operation that leverages simple bitwise arithmetic.

Key expansion (Part 1) generates a series of round keys from the original secret key using a lightweight mixing operation.

Key expansion (Part 2a) rotates the last column of the previous round key, moves the first byte to the end, then passes the column through the AES S‑box substitution.

Key expansion (Part 2b) XORs the transformed column with the round constant and finally XORs the result with the first column of the previous round key to produce the new first column.

Key expansion (Part 3) derives the remaining three columns by XOR‑ing each with the preceding column, noting that 128‑bit keys require ten rounds, 192‑bit keys eleven, and 256‑bit keys thirteen.

The middle rounds repeat four operations—SubBytes, ShiftRows, MixColumns, and AddRoundKey—exactly nine times for a 128‑bit key, with the number of repetitions depending on key length.

SubBytes replaces each byte in the state matrix with a corresponding value from the AES S‑box, providing non‑linear confusion.

ShiftRows cyclically shifts each row of the state matrix by a different offset, contributing to diffusion.

MixColumns treats each column as a polynomial and multiplies it by a fixed irreducible polynomial, further mixing the bits across the column.

AddRoundKey XORs the current state matrix with the round key generated in the key‑expansion phase.

The final round omits the MixColumns step because it does not increase security but would reduce performance.

Decryption is simply the inverse of the encryption process, and the article notes that CBC mode offers better security properties than ECB.

A brief reminder is given that a solid mathematical foundation (finite‑field arithmetic) is required to fully understand the underlying transformations.

For practical implementation, the article provides a Node.js helper to perform manual no‑padding handling:

function AESNoPadding(bodyData){
    var noPaddingBlockSize = 16;
    var realBodyLength = Buffer.byteLength(bodyData, 'utf8');
    if(realBodyLength % noPaddingBlockSize != 0){
        realBodyLength = realBodyLength + (noPaddingBlockSize - (realBodyLength % noPaddingBlockSize))
        var realDataBytesBuffer = new Buffer(realBodyLength);
        var bodyDataBytesBuffer = new Buffer(bodyData);
        bodyDataBytesBuffer.copy(realDataBytesBuffer,0,0,bodyDataBytesBuffer.length);
        return realDataBytesBuffer.toString('utf8');
    }else{
        return bodyData;
    }
}

It also shows the encryption routine and explains a subtle bug where the encrypted buffer was mistakenly converted to a string before being returned:

function AESEncryption(aesKey, aesAlgorithm, bodyData, iv) {
    try {
        var cipher = crypto.createCipheriv(aesAlgorithm, aesKey, iv);
        cipher.setAutoPadding(false);
        var realData = AESNoPaddingFix(bodyData);
        var crypted = cipher.update(realData, 'utf8', 'binary');
        crypted += cipher.final('binary'); // corrected: no .toString('utf8')
        crypted = new Buffer(crypted, 'binary');
        return crypted;
    } catch (err) {
        logger.info(err);
        return '';
    }
}

The article concludes with a reminder that understanding both the cryptographic theory and the concrete code paths is essential for reliable security development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Node.jsEncryptionInformation SecuritycryptographyAESKey Expansion
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.