Software Testing  

Implementing Encryption and Decryption in Cypress using Node.js Crypto Module

1. Setup Steps

Cypress runs in a Node.js environment, so you can use the built-in 'crypto' module without installing any additional packages.

2. Define Tasks in Cypress Configuration

You can define encryption and decryption tasks in the Cypress configuration file (e.g., cypress.config.js or cypress/plugins/index.js).

Example code

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // Store securely
const iv = crypto.randomBytes(16);  // Initialization vector

module.exports = (on, config) => {
  on('task', {
    encrypt(text) {
      const cipher = crypto.createCipheriv(algorithm, key, iv);
      let encrypted = cipher.update(text, 'utf8', 'hex');
      encrypted += cipher.final('hex');
      return `${iv.toString('hex')}:${encrypted}`;
    },
    decrypt(encryptedText) {
      const [ivHex, encrypted] = encryptedText.split(':');
      const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(ivHex, 'hex'));
      let decrypted = decipher.update(encrypted, 'hex', 'utf8');
      decrypted += decipher.final('utf8');
      return decrypted;
    }
  });
};

3. Usage in Cypress Test

Example test case using the defined tasks

describe('Secure Data Handling', () => {
  it('should encrypt and decrypt a password', () => {
    const password = 'MySecret123';

    cy.task('encrypt', password).then((encrypted) => {
      cy.log('Encrypted:', encrypted);

      cy.task('decrypt', encrypted).then((decrypted) => {
        expect(decrypted).to.equal(password);
      });
    });
  });
});

4. Best Practices for Handling Secrets Securely

  • Never hardcode encryption keys or IVs in your codebase.
  • Use environment variables or a secure secrets manager to store sensitive values.
  • Rotate encryption keys periodically.
  • Ensure encrypted values are not logged or exposed in test reports.