Skip to content
Home System Design Encryption at Rest and in Transit

Encryption at Rest and in Transit

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Security → Topic 6 of 10
Comprehensive guide to data security: Master TLS/HTTPS for data in motion and AES-256 for data at rest.
⚙️ Intermediate — basic System Design knowledge assumed
In this tutorial, you'll learn
Comprehensive guide to data security: Master TLS/HTTPS for data in motion and AES-256 for data at rest.
  • Transit encryption (TLS) protects data moving across networks — it is non-negotiable for modern web apps.
  • Rest encryption (AES-256) protects stored data — it is your last line of defense against physical theft and snapshot leaks.
  • Key Management is harder than Encryption: Store keys in a dedicated Secrets Manager (AWS KMS, Vault) and never hardcode them.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Encryption in transit uses TLS (HTTPS) to protect data moving between client and server — no one intercepting the network can read it. Encryption at rest uses AES to protect stored data — no one with physical disk access can read it without the key. Both are necessary: transit encryption alone does not protect against database breaches.

Encryption in Transit — TLS/HTTPS

Encryption in transit ensures that data remains confidential and untampered while moving across the wire. Modern standards rely on TLS (Transport Layer Security) 1.2 or 1.3. When a client connects via HTTPS, a handshake occurs where the server proves its identity via a Certificate Authority (CA) and both parties negotiate a symmetric session key.

In a Spring Boot environment, you must ensure that your microservices don't just 'accept' HTTPS, but actively enforce it. This includes rejecting insecure algorithms (like SSLv3 or TLS 1.0) and ensuring that internal service-to-service communication is also encrypted, often managed via a Service Mesh like Istio or Linkerd.

Example · JAVA
1234567891011121314151617181920212223242526272829303132
package io.thecodeforge.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Production-grade Security Configuration for io.thecodeforge
 * Forces HTTPS and sets Strict-Transport-Security (HSTS) headers.
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requiresChannel()
            .anyRequest()
            .requiresSecure() // Redirects all HTTP traffic to HTTPS
            .and()
            .headers()
            .httpStrictTransportSecurity()
            .includeSubDomains(true)
            .maxAgeInSeconds(31536000); // 1 Year HSTS policy
    }
}

// Pro-Tip: When using RestTemplate or WebClient to call external APIs,
// never disable SSL verification. Use a proper TrustStore if dealing with
// private CA certificates.
▶ Output
Enforces HTTPS/HSTS; protects against SSL Stripping attacks.

Encryption at Rest — Database and File Storage

Encryption at rest protects data stored on persistent media. There are two primary levels: Transparent Data Encryption (TDE) and Application-Level Encryption. TDE, offered by AWS RDS or Azure SQL, encrypts the entire database file on the disk. However, if a user gains access to the database via an SQL injection, TDE won't help because the database engine decrypts data for the authorized process.

For high-stakes data (like SSNs or API keys), we use Application-Level Encryption. Here, the data is encrypted before it ever hits the database driver. Even a root-level database admin cannot see the raw values without access to the keys stored in an external Secrets Manager like AWS KMS or HashiCorp Vault.

Example · JAVA
12345678910111213141516171819202122232425262728293031323334
package io.thecodeforge.security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Field-Level Encryption Utility
 * Standard: AES/GCM/NoPadding (Production recommended over ECB/CBC)
 */
public class EncryptionService {

    private static final String ALGORITHM = "AES";
    // In production, retrieve this key from AWS KMS or HashiCorp Vault
    private byte[] encryptionKey = System.getenv("DB_ENCRYPTION_KEY").getBytes();

    public String encrypt(String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(encryptionKey, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedValue = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedValue);
    }

    public String decrypt(String encryptedData) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(encryptionKey, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedValue = Base64.getDecoder().decode(encryptedData);
        return new String(cipher.doFinal(decodedValue));
    }
}

// usage: entity.setSsn(encryptionService.encrypt(rawSsn));
▶ Output
Decrypted: 123-45-6789

🎯 Key Takeaways

  • Transit encryption (TLS) protects data moving across networks — it is non-negotiable for modern web apps.
  • Rest encryption (AES-256) protects stored data — it is your last line of defense against physical theft and snapshot leaks.
  • Key Management is harder than Encryption: Store keys in a dedicated Secrets Manager (AWS KMS, Vault) and never hardcode them.
  • HSTS (Strict-Transport-Security) should be enabled to prevent 'SSL Stripping' attacks where HTTPS is downgraded to HTTP.
  • Defense in Depth: Use TDE for the hardware layer and Field-Level encryption for highly sensitive PII.

Interview Questions on This Topic

  • QExplain the 'Man-in-the-Middle' (MITM) attack and how TLS specifically prevents it.
  • QCompare Symmetric (AES) vs. Asymmetric (RSA/ECC) encryption. Which is typically used for data at rest and why?
  • QWhat are the security implications of disabling SSL certificate verification in a microservice-to-microservice call?
  • QHow would you implement 'Searchable Encryption' if a business requirement asks to find users by an encrypted Email address?
  • QWhat is the difference between an Initialization Vector (IV) and a Secret Key in AES GCM?

Frequently Asked Questions

If I use HTTPS, do I still need database encryption?

Absolutely. HTTPS only protects the 'tunnel' between the user and your server. Once the data reaches your application, it is in plaintext. If an attacker steals your database disk, accesses a backup file on S3, or uses a SQL injection exploit, they can read everything. Database-level and application-level encryption ensure that the data remains useless to an attacker even if they bypass the network perimeter.

What is the performance overhead of encrypting every database field?

Encryption does introduce CPU overhead, but for modern CPUs with AES-NI (Advanced Encryption Standard New Instructions), the cost is negligible for most applications. However, encrypting every single column can break database indexing and search capabilities. The standard practice is to encrypt only sensitive PII (Social Security Numbers, Credit Card details, Health records) rather than the entire schema.

What is key rotation and why is it important?

Key rotation involves generating a new version of an encryption key and using it for future operations. It is critical because it limits the 'blast radius' of a compromised key. If a key from 2024 is leaked, but you rotated in 2025, your 2025 data remains secure. Automated rotation in AWS KMS or HashiCorp Vault makes this process seamless without downtime.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousCSRF and XSS PreventionNext →What is Salting in Security? (Password Protection Explained)
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged