💡 Encrypting Payloads from Client-Side and Decrypting on Server-Side: A Step-by-Step Guide 🔒

Apurv upadhyay
4 min readOct 16, 2024

--

Encrypt and Decrypt payload

In today’s interconnected world, securing data during transmission between the client and server is crucial. One of the most effective methods is encrypting the payload on the client side and decrypting it on the server side. This ensures that sensitive information remains protected, even if intercepted. Here’s how you can implement it using AES encryption and CryptoJS.

🌐 How It Works:

1. Client-Side Encryption:

• The client encrypts the payload using a shared encryption key before sending the request to the server. This process ensures that only the intended recipient, with the correct key, can decrypt and access the data.

2. Server-Side Decryption:

• The server receives the encrypted payload and uses the same shared encryption key to decrypt it, allowing secure access to the original information.

This process helps maintain confidentiality, integrity, and authenticity of the data transmitted over the network.

🔧 Client-Side Encryption Code: Detailed Example

The following code demonstrates how to encrypt data on the client side using CryptoJS in JavaScript:

public async encryptedValue(plaintext: any) {
try {
const CryptoJS = require("crypto-js"); // Import CryptoJS library for encryption
let encryptionKey = "YOUR_ENCRYPTION_KEY_HERE"; // 🔑 Replace with your secure encryption key (Ensure it's stored securely)
const iv1 = CryptoJS.lib.WordArray.random(16); // Generate a random Initialization Vector (IV)

// Encrypt the plaintext using AES encryption (CBC mode and PKCS7 padding)
const ciphertext = CryptoJS.AES.encrypt(plaintext, encryptionKey, {
iv: iv1,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});

// Concatenate the IV and the ciphertext for secure transmission
const encryptedData = iv1.toString(CryptoJS.enc.Base64) + "|" + ciphertext.toString();
return encryptedData; // Return the encrypted payload
} catch (ex) {
this.logger.error({
module: "EncryptService",
method: "encryptedValue",
correlationId: "To be implemented",
error: ex,
});
return null;
}
}

📜 Explanation of Key Concepts:

CryptoJS Library: A popular library used in JavaScript for cryptographic functions like AES encryption.

AES (Advanced Encryption Standard): A strong symmetric encryption algorithm widely used for securing data.

Initialization Vector (IV): A randomly generated value used with the encryption algorithm to ensure that even if the same plaintext is encrypted multiple times, the output (ciphertext) is different each time. This protects against pattern recognition attacks.

Encryption Key: The secret key used for both encryption and decryption. It should be stored securely and not hard-coded directly in the codebase. Consider storing it in an environment variable or a secure key vault.

🔍 Server-Side Decryption Code: Detailed Example

The server uses the same encryption key and decrypts the payload by parsing the IV and ciphertext. Here’s how:

const CryptoJS = require("crypto-js");

public async decryptedValue(encryptedData: string) {
try {
// Split the encrypted data into the IV and ciphertext
const [ivBase64, ciphertext] = encryptedData.split("|");
const iv = CryptoJS.enc.Base64.parse(ivBase64); // Decode the IV from Base64 format
const encryptionKey = "YOUR_ENCRYPTION_KEY_HERE"; // 🔑 Same key used for encryption

// Decrypt the data using AES with the key and IV
const bytes = CryptoJS.AES.decrypt(ciphertext, encryptionKey, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});

// Convert the decrypted bytes to a UTF-8 string (original plaintext)
const plaintext = bytes.toString(CryptoJS.enc.Utf8);
return plaintext; // Return the original data
} catch (ex) {
this.logger.error({
module: "DecryptService",
method: "decryptedValue",
correlationId: "To be implemented",
error: ex,
});
return null;
}
}

🛡️ Why Use Encryption?

Data Confidentiality: By encrypting the payload, you ensure that only the intended recipient (with the correct decryption key) can access the information.

Data Integrity: Encrypted data can’t be tampered with during transmission without corrupting the decryption process, ensuring that the data received is authentic and unaltered.

Data Authenticity: Ensuring the encryption key is known only by the client and server helps verify that the data originates from a trusted source.

🔍 Best Practices for Secure Payload Transmission

Secure Storage of the Encryption Key:

• Never hard-code the encryption key directly in your code. Use environment variables or a secure secrets manager.

• Rotate the encryption key periodically to reduce the risk of exposure.

HTTPS Usage:

• Always use HTTPS alongside encryption to secure data in transit and prevent man-in-the-middle attacks.

• HTTPS ensures the transmission layer is secure, while encryption secures the payload itself.

Use Unique IVs:

• Always use a unique IV for each encryption operation to ensure that the same plaintext produces different ciphertexts, enhancing security.

Error Logging and Handling:

• Proper error logging, as shown in the examples, helps track encryption or decryption failures, which are important for debugging and security monitoring.

🔒 Benefits of Encrypting Client-Server Communication:

Prevents Data Leakage: If the data is intercepted during transmission, it remains unreadable without the decryption key.

Ensures Compliance: Many regulations (like GDPR, HIPAA) require that sensitive information be encrypted during transmission, making this approach compliant with industry standards.

Enhances Trust: Encrypting data shows a commitment to security, which is crucial for maintaining user trust in your application.

Example after encrypting payload

📌 Conclusion:

Encrypting payloads at the client side and decrypting them on the server side is an effective way to protect sensitive information during transmission. By leveraging AES encryption and following best practices, you can ensure that your application maintains confidentiality, integrity, and authenticity of the data.

Feel free to repost ♻️ if you found this helpful. For more great content on microservices, follow 🛠 Apurv Upadhyay.

#Encryption #CryptoJS #JavaScript #Security #ClientServer #WebDevelopment #DataProtection #ProgrammingTips #SecureCoding #SoftwareDevelopment

--

--

Apurv upadhyay
Apurv upadhyay

Written by Apurv upadhyay

Principal Software Engineer at PeerIslands • Microsoft Azure Certified Architect Expert & DevOps Specialist • 7x Azure Certified • ex-Microsoft, Bosch

No responses yet