Use of Weak Encryption Algorithms

Critical Risk Cryptographic Security
encryptioncryptographyweak-algorithmsdesmd5sha1rc4deprecated-cryptodata-protection

What it is

A critical vulnerability where applications use cryptographically weak encryption algorithms such as DES, 3DES, MD5, SHA-1, or RC4. These algorithms have known vulnerabilities and can be broken by modern computational methods, exposing sensitive data to unauthorized access through cryptographic attacks.

# VULNERABLE: Multiple weak encryption algorithms
import hashlib
import os
from Crypto.Cipher import DES3, DES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad

class VulnerableFileEncryption:
    def __init__(self, password):
        # Weak key derivation using MD5
        self.key = hashlib.md5(password.encode()).digest()[:8]  # DES key
        self.algorithm = 'DES'
    
    def encrypt_file(self, file_path, output_path):
        with open(file_path, 'rb') as infile:
            data = infile.read()
        
        # Using broken DES encryption
        cipher = DES.new(self.key, DES.MODE_ECB)  # ECB mode is also vulnerable
        
        # Weak padding
        padded_data = pad(data, DES.block_size)
        encrypted_data = cipher.encrypt(padded_data)
        
        with open(output_path, 'wb') as outfile:
            outfile.write(encrypted_data)
        
        # Weak integrity check using MD5
        checksum = hashlib.md5(encrypted_data).hexdigest()
        return checksum
    
    def decrypt_file(self, encrypted_path, output_path):
        with open(encrypted_path, 'rb') as infile:
            encrypted_data = infile.read()
        
        cipher = DES.new(self.key, DES.MODE_ECB)
        decrypted_data = unpad(cipher.decrypt(encrypted_data), DES.block_size)
        
        with open(output_path, 'wb') as outfile:
            outfile.write(decrypted_data)
    
    def generate_file_hash(self, file_path):
        # Using broken SHA-1 for file integrity
        with open(file_path, 'rb') as f:
            return hashlib.sha1(f.read()).hexdigest()
# SECURE: Strong encryption with AES-GCM and proper key derivation
import hashlib
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
import secrets

class SecureFileEncryption:
    def __init__(self, password):
        self.password = password.encode()
        
    def _derive_key(self, salt):
        # Strong key derivation using PBKDF2 with SHA-256
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,  # 256-bit key for AES-256
            salt=salt,
            iterations=100000,  # High iteration count
            backend=default_backend()
        )
        return kdf.derive(self.password)
    
    def encrypt_file(self, file_path, output_path):
        with open(file_path, 'rb') as infile:
            data = infile.read()
        
        # Generate random salt and nonce
        salt = secrets.token_bytes(32)
        nonce = secrets.token_bytes(12)  # 96-bit nonce for AES-GCM
        
        # Derive key from password
        key = self._derive_key(salt)
        
        # Use AES-GCM for authenticated encryption
        aesgcm = AESGCM(key)
        encrypted_data = aesgcm.encrypt(nonce, data, None)
        
        # Store salt, nonce, and encrypted data
        with open(output_path, 'wb') as outfile:
            outfile.write(salt + nonce + encrypted_data)
        
        # Strong integrity check using SHA-256
        with open(output_path, 'rb') as f:
            checksum = hashlib.sha256(f.read()).hexdigest()
        
        return checksum
    
    def decrypt_file(self, encrypted_path, output_path):
        with open(encrypted_path, 'rb') as infile:
            file_data = infile.read()
        
        # Extract salt, nonce, and encrypted data
        salt = file_data[:32]
        nonce = file_data[32:44]
        encrypted_data = file_data[44:]
        
        # Derive key from password and salt
        key = self._derive_key(salt)
        
        # Decrypt and verify authenticity
        aesgcm = AESGCM(key)
        try:
            decrypted_data = aesgcm.decrypt(nonce, encrypted_data, None)
        except Exception:
            raise ValueError("Decryption failed - file may be corrupted or password incorrect")
        
        with open(output_path, 'wb') as outfile:
            outfile.write(decrypted_data)
    
    def generate_file_hash(self, file_path):
        # Using secure SHA-256 for file integrity
        sha256_hash = hashlib.sha256()
        with open(file_path, 'rb') as f:
            for chunk in iter(lambda: f.read(4096), b""):
                sha256_hash.update(chunk)
        return sha256_hash.hexdigest()

💡 Why This Fix Works

The vulnerable implementation uses DES encryption (easily broken), ECB mode (reveals patterns), MD5 for key derivation (weak), and SHA-1 for integrity (deprecated). The secure version uses AES-256-GCM for authenticated encryption, PBKDF2 for secure key derivation, and SHA-256 for integrity checking.

-- VULNERABLE: Weak database encryption configuration
-- MySQL configuration with weak encryption
SET GLOBAL innodb_encryption_algorithm = 'DES';
SET GLOBAL innodb_encryption_key_id = 1;

-- Weak SSL configuration
SET GLOBAL ssl_cipher = 'DES-CBC3-SHA:RC4-SHA:RC4-MD5';
SET GLOBAL tls_version = 'TLSv1,TLSv1.1';

-- Application-level weak encryption
CREATE TABLE user_data (
    id INT PRIMARY KEY,
    username VARCHAR(255),
    -- Storing password hash using weak MD5
    password_hash CHAR(32) COMMENT 'MD5 hash',
    -- Storing credit card with weak encryption
    credit_card_encrypted BLOB COMMENT 'DES encrypted'
);

-- Weak encryption function
DELIMITER //
CREATE FUNCTION weak_encrypt(plaintext TEXT, key_str VARCHAR(255))
RETURNS BLOB
READS SQL DATA
DETERMINISTIC
BEGIN
    -- Using DES encryption (56-bit key)
    RETURN DES_ENCRYPT(plaintext, key_str);
END //
DELIMITER ;

-- Insert with weak encryption
INSERT INTO user_data (id, username, password_hash, credit_card_encrypted)
VALUES (
    1, 
    'john_doe',
    MD5('password123'),  -- Weak password hashing
    weak_encrypt('4532-1234-5678-9012', 'weak_key')  -- Weak encryption
);
-- SECURE: Strong database encryption configuration
-- MySQL configuration with strong encryption
SET GLOBAL innodb_encryption_algorithm = 'AES';
SET GLOBAL innodb_encryption_key_id = 1;
SET GLOBAL innodb_encryption_rotate_key_age = 90;  -- Regular key rotation

-- Strong SSL configuration
SET GLOBAL ssl_cipher = 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256';
SET GLOBAL tls_version = 'TLSv1.2,TLSv1.3';

-- Application-level strong encryption
CREATE TABLE user_data (
    id INT PRIMARY KEY,
    username VARCHAR(255),
    -- Using bcrypt for password hashing (handled by application)
    password_hash VARCHAR(255) COMMENT 'bcrypt hash',
    -- Using AES encryption with proper key management
    credit_card_encrypted BLOB COMMENT 'AES-256-GCM encrypted',
    credit_card_nonce BINARY(12) COMMENT 'AES-GCM nonce',
    credit_card_tag BINARY(16) COMMENT 'AES-GCM authentication tag',
    salt BINARY(32) COMMENT 'Salt for key derivation',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Secure encryption function using AES
DELIMITER //
CREATE FUNCTION secure_encrypt(plaintext TEXT, master_key VARCHAR(255), salt BINARY(32))
RETURNS JSON
READS SQL DATA
DETERMINISTIC
BEGIN
    DECLARE nonce BINARY(12);
    DECLARE encrypted_data BLOB;
    DECLARE auth_tag BINARY(16);
    
    -- Generate random nonce
    SET nonce = RANDOM_BYTES(12);
    
    -- Use AES-256-GCM encryption (pseudocode - actual implementation would be in application)
    -- This is conceptual as MySQL doesn't have built-in AES-GCM
    SET encrypted_data = AES_ENCRYPT(plaintext, CONCAT(master_key, salt));
    
    -- Return structured data
    RETURN JSON_OBJECT(
        'encrypted', TO_BASE64(encrypted_data),
        'nonce', TO_BASE64(nonce),
        'algorithm', 'AES-256-GCM'
    );
END //
DELIMITER ;

-- Better approach: Handle encryption in application layer
-- Application code would use proper AES-256-GCM encryption

-- Insert with secure practices (encryption done by application)
INSERT INTO user_data (
    id, 
    username, 
    password_hash, 
    credit_card_encrypted,
    credit_card_nonce,
    credit_card_tag,
    salt
) VALUES (
    1,
    'john_doe',
    '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBP4L6mCv2LWVW',  -- bcrypt hash
    UNHEX('A1B2C3D4...'),  -- AES-256-GCM encrypted data
    UNHEX('123456789ABC'),  -- 96-bit nonce
    UNHEX('DEF123456789'),  -- 128-bit authentication tag
    UNHEX('ABCDEF123456')   -- 256-bit salt
);

💡 Why This Fix Works

The vulnerable configuration uses DES encryption, weak SSL ciphers, MD5 for passwords, and insecure encryption functions. The secure version uses AES-256, strong TLS configuration, proper password hashing, and authenticated encryption with key rotation.

// C# - VULNERABLE: Weak token generation and validation
using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;

public class VulnerableTokenService
{
    private readonly string secretKey = "my_secret_key_123";
    
    // Weak random number generation
    private readonly Random random = new Random();
    
    public string GenerateToken(int userId, string username)
    {
        // Weak token structure
        string tokenData = $"{userId}:{username}:{DateTime.UtcNow.Ticks}";
        
        // Using weak MD5 for token generation
        using (var md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(tokenData + secretKey);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            
            return Convert.ToBase64String(hashBytes);
        }
    }
    
    public bool ValidateToken(string token, int expectedUserId)
    {
        try
        {
            // Weak validation using timing-vulnerable string comparison
            string expectedToken = GenerateTokenForValidation(expectedUserId);
            return token == expectedToken;  // Timing attack vulnerable!
        }
        catch
        {
            return false;
        }
    }
    
    private string GenerateTokenForValidation(int userId)
    {
        // Regenerating token for validation (inefficient and weak)
        using (var md5 = MD5.Create())
        {
            string tokenData = $"{userId}:validation:{DateTime.UtcNow.Ticks}";
            byte[] inputBytes = Encoding.UTF8.GetBytes(tokenData + secretKey);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            
            return Convert.ToBase64String(hashBytes);
        }
    }
    
    public string EncryptSensitiveData(string data)
    {
        // Using weak DES encryption
        using (var des = DES.Create())
        {
            des.Key = Encoding.UTF8.GetBytes(secretKey.Substring(0, 8));
            des.IV = new byte[8]; // Zero IV - very weak!
            des.Mode = CipherMode.ECB; // ECB mode is vulnerable
            
            using (var encryptor = des.CreateEncryptor())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(data);
                byte[] encrypted = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
                return Convert.ToBase64String(encrypted);
            }
        }
    }
}
// C# - SECURE: Strong token generation with proper cryptography
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public class SecureTokenService
{
    private readonly byte[] secretKey;
    private readonly RNGCryptoServiceProvider rng;
    
    public SecureTokenService()
    {
        // Generate cryptographically secure key
        secretKey = new byte[64]; // 512-bit key
        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(secretKey);
        }
        
        this.rng = new RNGCryptoServiceProvider();
    }
    
    public string GenerateJwtToken(int userId, string username, TimeSpan expiration)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = new SymmetricSecurityKey(secretKey);
        
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim("userId", userId.ToString()),
                new Claim("username", username),
                new Claim("jti", GenerateSecureRandomId()) // Unique token ID
            }),
            Expires = DateTime.UtcNow.Add(expiration),
            Issuer = "SecureApp",
            Audience = "SecureApp",
            SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
        };
        
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
    
    public ClaimsPrincipal ValidateToken(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = new SymmetricSecurityKey(secretKey);
        
        var validationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = key,
            ValidateIssuer = true,
            ValidIssuer = "SecureApp",
            ValidateAudience = true,
            ValidAudience = "SecureApp",
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero // No tolerance for clock skew
        };
        
        try
        {
            var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
            return principal;
        }
        catch
        {
            return null; // Token invalid
        }
    }
    
    public string EncryptSensitiveData(string data)
    {
        using (var aes = Aes.Create())
        {
            aes.KeySize = 256; // AES-256
            aes.Mode = CipherMode.GCM; // Authenticated encryption
            
            // Generate random key and nonce
            byte[] key = new byte[32]; // 256-bit key
            byte[] nonce = new byte[12]; // 96-bit nonce for GCM
            byte[] tag = new byte[16]; // 128-bit authentication tag
            
            rng.GetBytes(key);
            rng.GetBytes(nonce);
            
            using (var cipher = new AesGcm(key))
            {
                byte[] plaintext = Encoding.UTF8.GetBytes(data);
                byte[] ciphertext = new byte[plaintext.Length];
                
                cipher.Encrypt(nonce, plaintext, ciphertext, tag);
                
                // Combine key, nonce, tag, and ciphertext
                var result = new
                {
                    Key = Convert.ToBase64String(key),
                    Nonce = Convert.ToBase64String(nonce),
                    Tag = Convert.ToBase64String(tag),
                    Ciphertext = Convert.ToBase64String(ciphertext),
                    Algorithm = "AES-256-GCM"
                };
                
                return JsonSerializer.Serialize(result);
            }
        }
    }
    
    public string DecryptSensitiveData(string encryptedData)
    {
        var data = JsonSerializer.Deserialize<dynamic>(encryptedData);
        
        byte[] key = Convert.FromBase64String(data.GetProperty("Key").GetString());
        byte[] nonce = Convert.FromBase64String(data.GetProperty("Nonce").GetString());
        byte[] tag = Convert.FromBase64String(data.GetProperty("Tag").GetString());
        byte[] ciphertext = Convert.FromBase64String(data.GetProperty("Ciphertext").GetString());
        
        using (var cipher = new AesGcm(key))
        {
            byte[] plaintext = new byte[ciphertext.Length];
            
            try
            {
                cipher.Decrypt(nonce, ciphertext, tag, plaintext);
                return Encoding.UTF8.GetString(plaintext);
            }
            catch (CryptographicException)
            {
                throw new InvalidOperationException("Decryption failed - data may be corrupted");
            }
        }
    }
    
    private string GenerateSecureRandomId()
    {
        byte[] randomBytes = new byte[32];
        rng.GetBytes(randomBytes);
        
        using (var sha256 = SHA256.Create())
        {
            byte[] hash = sha256.ComputeHash(randomBytes);
            return Convert.ToBase64String(hash);
        }
    }
    
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            rng?.Dispose();
        }
    }
}

💡 Why This Fix Works

The vulnerable implementation uses MD5 for token generation, DES encryption, weak random number generation, and timing-vulnerable comparisons. The secure version uses JWT with HMAC-SHA256, AES-256-GCM for encryption, cryptographically secure random number generation, and proper token validation.

Why it happens

Developers continue using Data Encryption Standard (DES) or Triple DES (3DES) for encrypting sensitive data. DES uses a 56-bit key which can be brute-forced in hours, while 3DES is deprecated due to performance issues and birthday attacks. Modern attacks can break these algorithms relatively easily.

Root causes

Legacy DES/3DES Encryption Implementation

Developers continue using Data Encryption Standard (DES) or Triple DES (3DES) for encrypting sensitive data. DES uses a 56-bit key which can be brute-forced in hours, while 3DES is deprecated due to performance issues and birthday attacks. Modern attacks can break these algorithms relatively easily.

Preview example – JAVA
// Java - VULNERABLE: Using DES encryption
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class WeakEncryption {
    public byte[] encryptData(byte[] data, SecretKey key) throws Exception {
        // DES is cryptographically broken!
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }
    
    public SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        return keyGen.generateKey(); // Only 56-bit effective key length
    }
}

Weak Hash Functions for Cryptographic Operations

Applications using MD5 or SHA-1 for cryptographic purposes like digital signatures, certificate validation, or password hashing. MD5 has known collision vulnerabilities, and SHA-1 has been practically broken. These functions should not be used for any security-critical operations.

Preview example – PYTHON
// Python - VULNERABLE: Using MD5 and SHA-1 for security
import hashlib
import hmac

def sign_data(data, secret_key):
    # MD5 is cryptographically broken - collision attacks possible!
    return hmac.new(secret_key.encode(), data.encode(), hashlib.md5).hexdigest()

def verify_password(password, stored_hash):
    # SHA-1 is deprecated and vulnerable to collision attacks
    password_hash = hashlib.sha1(password.encode()).hexdigest()
    return password_hash == stored_hash

def generate_token(user_id):
    # Weak hash for token generation
    token_data = f"{user_id}:{time.time()}"
    return hashlib.md5(token_data.encode()).hexdigest()

Deprecated RC4 Stream Cipher Usage

RC4 stream cipher is still found in legacy applications and some TLS configurations. RC4 has multiple biases and vulnerabilities that make it unsuitable for secure communications. It's been deprecated by major standards organizations and should be completely avoided.

Preview example – JAVASCRIPT
// Node.js - VULNERABLE: RC4 cipher implementation
const crypto = require('crypto');

class LegacyEncryption {
    constructor(key) {
        this.algorithm = 'rc4'; // RC4 is cryptographically broken!
        this.key = key;
    }
    
    encrypt(text) {
        const cipher = crypto.createCipher(this.algorithm, this.key);
        let encrypted = cipher.update(text, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return encrypted;
    }
    
    decrypt(encryptedText) {
        const decipher = crypto.createDecipher(this.algorithm, this.key);
        let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    }
}

Weak Symmetric Encryption in Configuration

Configuration files or application settings that specify weak encryption algorithms, often for backward compatibility. This includes SSL/TLS configurations that allow weak ciphers, or database encryption settings using deprecated algorithms.

Preview example – NGINX
# SSL Configuration - VULNERABLE: Allowing weak ciphers
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'DES-CBC3-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA';
ssl_prefer_server_ciphers on;

# Database encryption - VULNERABLE
encrypt_algorithm = 'DES'
key_length = 56
hash_function = 'MD5'

Fixes

1

Migrate to AES with Strong Modes

Replace DES, 3DES, and other weak symmetric encryption with AES (Advanced Encryption Standard) using secure modes like GCM or CBC with proper IV handling. AES-256-GCM provides both confidentiality and authenticity, making it ideal for most encryption needs.

View implementation – JAVA
// Java - SECURE: Using AES-GCM encryption
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;

public class SecureEncryption {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/GCM/NoPadding";
    private static final int GCM_IV_LENGTH = 12;
    private static final int GCM_TAG_LENGTH = 16;
    
    public EncryptionResult encryptData(byte[] data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        
        byte[] iv = new byte[GCM_IV_LENGTH];
        new SecureRandom().nextBytes(iv);
        
        GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
        
        byte[] encrypted = cipher.doFinal(data);
        return new EncryptionResult(encrypted, iv);
    }
    
    public SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(256); // Use 256-bit AES
        return keyGen.generateKey();
    }
}
2

Upgrade to SHA-256/SHA-3 Hash Functions

Replace MD5 and SHA-1 with SHA-256, SHA-384, SHA-512, or SHA-3 family hash functions. For HMAC operations, use HMAC-SHA256 or stronger. For password hashing, use specialized functions like bcrypt, scrypt, or Argon2.

View implementation – PYTHON
# Python - SECURE: Using strong hash functions
import hashlib
import hmac
import bcrypt
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def sign_data(data, secret_key):
    # Use HMAC-SHA256 for message authentication
    return hmac.new(
        secret_key.encode(), 
        data.encode(), 
        hashlib.sha256
    ).hexdigest()

def hash_password(password):
    # Use bcrypt for password hashing
    salt = bcrypt.gensalt(rounds=12)
    return bcrypt.hashpw(password.encode('utf-8'), salt)

def verify_password(password, stored_hash):
    return bcrypt.checkpw(password.encode('utf-8'), stored_hash)

def generate_secure_token(user_id, secret):
    # Use SHA-256 for token generation
    token_data = f"{user_id}:{time.time()}:{os.urandom(16).hex()}"
    return hashlib.sha256(token_data.encode()).hexdigest()
3

Implement ChaCha20-Poly1305 for Stream Encryption

For applications requiring stream encryption, replace RC4 with ChaCha20-Poly1305, which provides both encryption and authentication. This algorithm is modern, fast, and cryptographically secure.

View implementation – JAVASCRIPT
// Node.js - SECURE: Using ChaCha20-Poly1305
const crypto = require('crypto');

class SecureStreamEncryption {
    constructor() {
        this.algorithm = 'chacha20-poly1305';
    }
    
    generateKey() {
        return crypto.randomBytes(32); // 256-bit key
    }
    
    encrypt(text, key) {
        const nonce = crypto.randomBytes(12); // 96-bit nonce for ChaCha20
        const cipher = crypto.createCipher(this.algorithm, key, nonce);
        
        let encrypted = cipher.update(text, 'utf8');
        cipher.final();
        
        const tag = cipher.getAuthTag();
        
        return {
            encrypted: encrypted,
            nonce: nonce,
            tag: tag
        };
    }
    
    decrypt(encryptedData, key) {
        const decipher = crypto.createDecipher(
            this.algorithm, 
            key, 
            encryptedData.nonce
        );
        
        decipher.setAuthTag(encryptedData.tag);
        
        let decrypted = decipher.update(encryptedData.encrypted, null, 'utf8');
        decipher.final();
        
        return decrypted;
    }
}
4

Update SSL/TLS Configuration

Configure servers to only support strong TLS versions (1.2+) and cipher suites. Disable all weak ciphers including those using DES, RC4, MD5, and export-grade encryption. Use tools like SSL Labs to test configuration strength.

View implementation – NGINX
# Nginx - SECURE: Strong SSL/TLS configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;

# Database encryption - SECURE
encrypt_algorithm = 'AES-256-GCM'
key_length = 256
hash_function = 'SHA-256'

Detect This Vulnerability in Your Code

Sourcery automatically identifies use of weak encryption algorithms and many other security issues in your codebase.