# DES (Data Encryption Standard)

### **📋 Índice**

1. Fundamentos do DES
2. Arquitetura e Estrutura
3. Função F e S-Boxes
4. Key Schedule
5. Implementação Prática
6. Modos de Operação
7. Vulnerabilidades e Ataques
8. 3DES (Triple DES)
9. DES vs AES
10. Legado e Migração
11. Checklists de Segurança

***

### 🔍 **Fundamentos do DES**

#### **O que é DES?**

**Data Encryption Standard (DES)** é um algoritmo de cifragem simétrica desenvolvido pela IBM nos anos 1970 e adotado como padrão federal dos EUA (FIPS 46-3) em 1977. Foi o primeiro algoritmo de criptografia a ser certificado para uso governamental e comercial.

#### **Características Principais**

```yaml
Especificações DES:
  Tamanho do bloco: 64 bits (8 bytes)
  Tamanho da chave: 56 bits efetivos (64 bits com paridade)
  Rodadas: 16 rodadas
  Estrutura: Rede de Feistel
  Tamanho do espaço de chaves: 2^56 (~7.2×10^16)

Segurança Atual:
  ❌ Vulnerável a brute force (1999: 22 horas)
  ❌ Vulnerável a ataques lineares e diferenciais
  ✅ Apenas seguro em modo 3DES

Performance (software):
  DES: ~50 MB/s (CPU moderno)
  3DES: ~15 MB/s
  AES: ~300 MB/s
```

#### **Contexto Histórico**

```mermaid
timeline
    title Evolução do DES
    1973 : NBS (atual NIST)<br>solicita algoritmo<br>de criptografia
    1974 : IBM submete<br>Lucifer (base do DES)
    1976 : DES é adotado<br>como padrão federal
    1977 : FIPS 46-3 publicado
    1990 : Descoberta de<br>criptoanálise diferencial
    1998 : EFF quebra DES<br>em 56 horas (Deep Crack)
    1999 : DES quebrado<br>em 22 horas
    2001 : AES substitui DES
    2005 : DES retirado<br>como padrão FIPS
```

#### **Rede de Feistel**

```mermaid
graph TD
    subgraph "Rede de Feistel - Rodada i"
        A[Entrada: Li-1, Ri-1] --> B[Função F]
        B --> C[XOR]
        C --> D[Saída: Ri, Li]
    end
    
    subgraph "Processo Completo"
        E[Bloco 64 bits] --> F[IP - Permutação Inicial]
        F --> G[Rodada 1]
        G --> H[...]
        H --> I[Rodada 16]
        I --> J[FP - Permutação Final]
        J --> K[Cifra 64 bits]
    end
    
    style B fill:#ffcc99
    style G fill:#99ccff
```

***

### 🏗️ **Arquitetura e Estrutura**

#### **Permutação Inicial (IP) e Final (FP)**

```python
#!/usr/bin/env python3
# des_initial_perm.py - Permutações do DES

class DESPermutations:
    """Permutações do DES: IP, FP e Expansão"""
    
    # Permutação Inicial (IP)
    IP = [
        58, 50, 42, 34, 26, 18, 10, 2,
        60, 52, 44, 36, 28, 20, 12, 4,
        62, 54, 46, 38, 30, 22, 14, 6,
        64, 56, 48, 40, 32, 24, 16, 8,
        57, 49, 41, 33, 25, 17, 9, 1,
        59, 51, 43, 35, 27, 19, 11, 3,
        61, 53, 45, 37, 29, 21, 13, 5,
        63, 55, 47, 39, 31, 23, 15, 7
    ]
    
    # Permutação Final (FP) - inversa de IP
    FP = [
        40, 8, 48, 16, 56, 24, 64, 32,
        39, 7, 47, 15, 55, 23, 63, 31,
        38, 6, 46, 14, 54, 22, 62, 30,
        37, 5, 45, 13, 53, 21, 61, 29,
        36, 4, 44, 12, 52, 20, 60, 28,
        35, 3, 43, 11, 51, 19, 59, 27,
        34, 2, 42, 10, 50, 18, 58, 26,
        33, 1, 41, 9, 49, 17, 57, 25
    ]
    
    # Tabela de Expansão (32 bits -> 48 bits)
    EXPANSION = [
        32, 1, 2, 3, 4, 5,
        4, 5, 6, 7, 8, 9,
        8, 9, 10, 11, 12, 13,
        12, 13, 14, 15, 16, 17,
        16, 17, 18, 19, 20, 21,
        20, 21, 22, 23, 24, 25,
        24, 25, 26, 27, 28, 29,
        28, 29, 30, 31, 32, 1
    ]
    
    # Permutação P (32 bits)
    P_PERM = [
        16, 7, 20, 21, 29, 12, 28, 17,
        1, 15, 23, 26, 5, 18, 31, 10,
        2, 8, 24, 14, 32, 27, 3, 9,
        19, 13, 30, 6, 22, 11, 4, 25
    ]
    
    @staticmethod
    def permute(block, table):
        """Aplicar permutação a um bloco de 64 bits"""
        result = 0
        for i, pos in enumerate(table):
            bit = (block >> (64 - pos)) & 1
            result = (result << 1) | bit
        return result
    
    @staticmethod
    def expansion(block_32):
        """Expansão de 32 bits para 48 bits"""
        result = 0
        for i, pos in enumerate(DESPermutations.EXPANSION):
            bit = (block_32 >> (32 - pos)) & 1
            result = (result << 1) | bit
        return result

# Demonstração
print("Permutações do DES")
print("=" * 60)
print(f"IP: {DESPermutations.IP[:8]}...")
print(f"FP: {DESPermutations.FP[:8]}...")
print(f"Expansion: {DESPermutations.EXPANSION[:8]}...")
```

***

### 🔧 **Função F e S-Boxes**

#### **Estrutura da Função F**

```python
#!/usr/bin/env python3
# des_f_function.py - Função F do DES

class DESFunctionF:
    """Implementação da função F do DES"""
    
    # S-Boxes (8 boxes, cada uma 4x16)
    S_BOXES = [
        # S1
        [
            [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
            [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
            [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
            [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]
        ],
        # S2 a S8 (omitidas para brevidade)
        # ... tabelas completas
    ]
    
    @staticmethod
    def s_box_lookup(s_box_num, input_6bits):
        """Lookup em S-Box (6 bits -> 4 bits)"""
        # Linha: bits 0 e 5
        row = ((input_6bits >> 5) & 1) | ((input_6bits & 1) << 1)
        # Coluna: bits 1-4
        col = (input_6bits >> 1) & 0xF
        
        return DESFunctionF.S_BOXES[s_box_num][row][col]
    
    @staticmethod
    def f_function(right_32, subkey_48):
        """Função F: F(R, K)"""
        # 1. Expansão de 32 para 48 bits
        expanded = DESPermutations.expansion(right_32)
        
        # 2. XOR com subkey
        xored = expanded ^ subkey_48
        
        # 3. S-Box substitution (48 -> 32 bits)
        output_32 = 0
        for i in range(8):
            # Pegar 6 bits da posição i
            six_bits = (xored >> (42 - 6*i)) & 0x3F
            four_bits = DESFunctionF.s_box_lookup(i, six_bits)
            output_32 = (output_32 << 4) | four_bits
        
        # 4. Permutação P
        result = DESPermutations.permute(output_32, DESPermutations.P_PERM)
        
        return result

print("Função F do DES")
print("=" * 60)
print("Estrutura: Expansão → XOR → S-Boxes → Permutação P")
print("8 S-Boxes: cada uma converte 6 bits em 4 bits")
```

#### **Tabelas S-Box Completas**

```c
// sboxes_des.c - Tabelas S-Box do DES

// S1
static const uint8_t S1[4][16] = {
    {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
    {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
    {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
    {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}
};

// S2
static const uint8_t S2[4][16] = {
    {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
    {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
    {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
    {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}
};

// S3 a S8 são similares
// ...
```

***

### 🔑 **Key Schedule**

#### **Geração de Subchaves**

```python
#!/usr/bin/env python3
# des_key_schedule.py - Key Schedule do DES

class DESKeySchedule:
    """Geração de subchaves do DES (16 rodadas)"""
    
    # Permutação PC-1 (64 bits -> 56 bits)
    PC1 = [
        57, 49, 41, 33, 25, 17, 9,
        1, 58, 50, 42, 34, 26, 18,
        10, 2, 59, 51, 43, 35, 27,
        19, 11, 3, 60, 52, 44, 36,
        63, 55, 47, 39, 31, 23, 15,
        7, 62, 54, 46, 38, 30, 22,
        14, 6, 61, 53, 45, 37, 29,
        21, 13, 5, 28, 20, 12, 4
    ]
    
    # Permutação PC-2 (56 bits -> 48 bits)
    PC2 = [
        14, 17, 11, 24, 1, 5, 3, 28,
        15, 6, 21, 10, 23, 19, 12, 4,
        26, 8, 16, 7, 27, 20, 13, 2,
        41, 52, 31, 37, 47, 55, 30, 40,
        51, 45, 33, 48, 44, 49, 39, 56,
        34, 53, 46, 42, 50, 36, 29, 32
    ]
    
    # Deslocamentos por rodada
    SHIFTS = [
        1, 1, 2, 2, 2, 2, 2, 2,
        1, 2, 2, 2, 2, 2, 2, 1
    ]
    
    def __init__(self, key_64):
        self.key_64 = key_64
        self.subkeys = []
        self._generate_subkeys()
    
    def _permute_key(self, key, table, out_bits):
        """Permutar chave"""
        result = 0
        for i, pos in enumerate(table):
            bit = (key >> (64 - pos)) & 1
            result = (result << 1) | bit
        return result
    
    def _split_key(self, key_56):
        """Dividir chave em C0 (28 bits) e D0 (28 bits)"""
        c = (key_56 >> 28) & 0xFFFFFFF
        d = key_56 & 0xFFFFFFF
        return c, d
    
    def _left_shift(self, value, shift, bits=28):
        """Rotação à esquerda"""
        mask = (1 << bits) - 1
        return ((value << shift) | (value >> (bits - shift))) & mask
    
    def _generate_subkeys(self):
        """Gerar 16 subchaves de 48 bits"""
        # PC-1: 64 bits -> 56 bits
        key_56 = self._permute_key(self.key_64, self.PC1, 56)
        
        # Dividir em C e D
        c, d = self._split_key(key_56)
        
        # Gerar subchaves para cada rodada
        for round_num in range(16):
            # Deslocamento
            shift = self.SHIFTS[round_num]
            c = self._left_shift(c, shift, 28)
            d = self._left_shift(d, shift, 28)
            
            # Combinar C e D (56 bits)
            cd = (c << 28) | d
            
            # PC-2: 56 bits -> 48 bits
            subkey = self._permute_key(cd, self.PC2, 48)
            self.subkeys.append(subkey)
    
    def get_subkey(self, round_num):
        """Obter subchave da rodada (0-indexed)"""
        return self.subkeys[round_num]

# Demonstração
key = 0x133457799BBCDFF1  # Chave de exemplo
key_schedule = DESKeySchedule(key)

print("Key Schedule do DES")
print("=" * 60)
print(f"Chave original: {key:016x}")
for i in range(16):
    subkey = key_schedule.get_subkey(i)
    print(f"Rodada {i+1:2d}: {subkey:012x}")
```

***

### 💻 **Implementação Prática**

#### **DES Completo em Python**

```python
#!/usr/bin/env python3
# des_complete.py - Implementação completa do DES

class DES:
    """Implementação completa do DES"""
    
    # Tabelas (IP, FP, S-Boxes, etc.)
    IP = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
          62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
          57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
          61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]
    
    FP = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
          38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
          36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
          34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25]
    
    # S-Boxes (8 boxes)
    S_BOXES = [
        # S1
        [
            [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
            [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
            [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
            [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]
        ],
        # S2 a S8 (implementação completa necessária)
        # ...
    ]
    
    # Permutação P
    P = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
         2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25]
    
    # Tabela de Expansão
    E = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13,
         12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23,
         24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1]
    
    def __init__(self, key):
        self.key = key
        self.subkeys = self._generate_subkeys()
    
    def _permute(self, block, table):
        """Aplicar permutação"""
        result = 0
        for i, pos in enumerate(table):
            bit = (block >> (64 - pos)) & 1
            result = (result << 1) | bit
        return result
    
    def _generate_subkeys(self):
        """Gerar subchaves (16 rodadas)"""
        # Implementação simplificada
        subkeys = []
        # ... (key schedule completo)
        return subkeys
    
    def _f_function(self, right, subkey):
        """Função F"""
        # Expansão
        expanded = self._permute_32_to_48(right, self.E)
        
        # XOR com subkey
        xored = expanded ^ subkey
        
        # S-Boxes
        output = 0
        for i in range(8):
            six_bits = (xored >> (42 - 6*i)) & 0x3F
            s_box = self.S_BOXES[i]
            row = ((six_bits >> 5) & 1) | ((six_bits & 1) << 1)
            col = (six_bits >> 1) & 0xF
            four_bits = s_box[row][col]
            output = (output << 4) | four_bits
        
        # Permutação P
        result = self._permute_32(output, self.P)
        return result
    
    def _permute_32_to_48(self, value, table):
        """Permutar 32 bits para 48 bits"""
        result = 0
        for i, pos in enumerate(table):
            bit = (value >> (32 - pos)) & 1
            result = (result << 1) | bit
        return result
    
    def _permute_32(self, value, table):
        """Permutar 32 bits"""
        result = 0
        for i, pos in enumerate(table):
            bit = (value >> (32 - pos)) & 1
            result = (result << 1) | bit
        return result
    
    def encrypt_block(self, plaintext):
        """Cifrar um bloco de 64 bits"""
        # Permutação inicial
        block = self._permute(plaintext, self.IP)
        
        # Dividir em L e R
        left = (block >> 32) & 0xFFFFFFFF
        right = block & 0xFFFFFFFF
        
        # 16 rodadas
        for i in range(16):
            temp = right
            right = left ^ self._f_function(right, self.subkeys[i])
            left = temp
        
        # Combinar (swap final)
        block = (right << 32) | left
        
        # Permutação final
        ciphertext = self._permute(block, self.FP)
        
        return ciphertext
    
    def decrypt_block(self, ciphertext):
        """Decifrar um bloco de 64 bits"""
        # Similar ao encrypt, mas com subchaves em ordem reversa
        # ... (implementação similar)
        pass

# Teste
key = 0x133457799BBCDFF1
plaintext = 0x0123456789ABCDEF

des = DES(key)
ciphertext = des.encrypt_block(plaintext)

print("DES Implementation")
print("=" * 60)
print(f"Key: {key:016x}")
print(f"Plaintext: {plaintext:016x}")
print(f"Ciphertext: {ciphertext:016x}")
```

***

### ⚔️ **Vulnerabilidades e Ataques**

#### **Brute Force Attack**

```python
#!/usr/bin/env python3
# des_bruteforce.py - Simulação de brute force

import time

class DESBruteForce:
    """Simulação de ataque de força bruta ao DES"""
    
    @staticmethod
    def estimate_time():
        """Estimar tempo de brute force"""
        print("Estimativa de tempo para brute force DES")
        print("=" * 60)
        
        # 2^56 combinações
        total_keys = 2**56
        print(f"Total de chaves: {total_keys:,.0f} (~{total_keys/1e16:.2f}×10^16)")
        
        # Velocidades de teste
        speeds = {
            "CPU (1997)": 10_000,      # 10k chaves/segundo
            "CPU (2000)": 100_000,     # 100k chaves/segundo
            "GPU (2010)": 10_000_000,  # 10M chaves/segundo
            "FPGA (2015)": 1_000_000_000,  # 1B chaves/segundo
            "ASIC (2019)": 100_000_000_000  # 100B chaves/segundo
        }
        
        for device, speed in speeds.items():
            seconds = total_keys / speed
            hours = seconds / 3600
            days = hours / 24
            years = days / 365
            
            print(f"\n{device}: {speed:,} chaves/segundo")
            print(f"  {years:.1f} anos")
    
    @staticmethod
    def deep_crack_success():
        """Deep Crack (1998) - 56 horas"""
        print("\n" + "=" * 60)
        print("Deep Crack (EFF - 1998)")
        print("  Hardware: 1,856 chips custom")
        print("  Velocidade: 88 bilhões de chaves/segundo")
        print("  Tempo: 56 horas")
        print("  Custo: $250,000")
    
    @staticmethod
    def copacobana_success():
        """Copacobana (2006) - 1 semana"""
        print("\n" + "=" * 60)
        print("Copacobana (2006)")
        print("  Hardware: 120 FPGAs")
        print("  Velocidade: 1 trilhão de chaves/segundo")
        print("  Tempo: 1 semana")
        print("  Custo: $10,000")

# Executar
DESBruteForce.estimate_time()
DESBruteForce.deep_crack_success()
DESBruteForce.copacobana_success()
```

#### **Criptoanálise Diferencial**

```python
#!/usr/bin/env python3
# differential_cryptanalysis.py - Criptoanálise diferencial

class DifferentialCryptanalysis:
    """Simulação de criptoanálise diferencial no DES"""
    
    @staticmethod
    def explain_attack():
        """Explicar o ataque"""
        print("Criptoanálise Diferencial - DES")
        print("=" * 60)
        
        print("""
Descoberta: Biham e Shamir (1990)

Princípio:
  1. Escolher pares de plaintext com diferença específica (ΔP)
  2. Observar diferença resultante no ciphertext (ΔC)
  3. Analisar propagação de diferenças através das S-Boxes
  4. Inferir bits da chave

Complexidade:
  • DES completo: 2^47 plaintexts escolhidos
  • DES com 8 rodadas: 2^14 plaintexts
  • DES com 16 rodadas: 2^47 plaintexts (prático)

Características:
  • S-Boxes têm características diferenciais
  • Algumas diferenças têm alta probabilidade
  • Permite recuperar chave mais rápido que brute force
""")
    
    @staticmethod
    def difference_distribution_table():
        """Tabela de distribuição de diferenças da S1"""
        print("\nTabela de Distribuição de Diferenças - S1")
        print("(exemplo: entrada 0x34)")
        
        # Simulação de características diferenciais
        differences = {
            0x01: 0.25,
            0x02: 0.19,
            0x04: 0.16,
            0x08: 0.22,
            0x10: 0.18,
            0x20: 0.20
        }
        
        for diff, prob in differences.items():
            print(f"  ΔX = 0x{diff:02x}: probabilidade = {prob:.2f}")

# Executar
DifferentialCryptanalysis.explain_attack()
DifferentialCryptanalysis.difference_distribution_table()
```

***

### 🔄 **3DES (Triple DES)**

#### **Modos de Operação do 3DES**

```python
#!/usr/bin/env python3
# triple_des.py - Triple DES

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

class TripleDES:
    """Implementação e análise do 3DES"""
    
    @staticmethod
    def modes():
        """Modos de operação do 3DES"""
        print("Modos de operação do 3DES")
        print("=" * 60)
        
        modes_3des = {
            "3TDEA": {
                "chaves": 3,
                "tamanho": "168 bits",
                "operação": "E-E-E (3 chaves diferentes)",
                "segurança": "Alta (112 bits efetivos)"
            },
            "2TDEA": {
                "chaves": 2,
                "tamanho": "112 bits",
                "operação": "E-E-E (K1=K3)",
                "segurança": "Média (80 bits efetivos)"
            },
            "DES-EEE3": {
                "chaves": 3,
                "tamanho": "168 bits",
                "operação": "E-E-E (encrypt-encrypt-encrypt)",
                "segurança": "Alta"
            },
            "DES-EDE3": {
                "chaves": 3,
                "tamanho": "168 bits",
                "operação": "E-D-E (encrypt-decrypt-encrypt)",
                "segurança": "Alta (recomendado)"
            }
        }
        
        for mode, info in modes_3des.items():
            print(f"\n{mode}:")
            for key, value in info.items():
                print(f"  {key}: {value}")
    
    @staticmethod
    def security_analysis():
        """Análise de segurança do 3DES"""
        print("\n" + "=" * 60)
        print("Análise de Segurança do 3DES")
        
        attacks = {
            "Meet-in-the-Middle": "2^112 operações",
            "Brute Force": "2^112 (2TDEA) / 2^168 (3TDEA)",
            "Sweet32": "Vulnerável a birthday attack (64-bit block)",
            "Quantum (Grover)": "2^56 (3TDEA) - risco futuro"
        }
        
        for attack, complexity in attacks.items():
            print(f"  {attack}: {complexity}")
    
    @staticmethod
    def performance_comparison():
        """Comparação de performance"""
        print("\n" + "=" * 60)
        print("Performance (MB/s - CPU moderno)")
        print("  DES:  ~50 MB/s")
        print("  3DES: ~15 MB/s")
        print("  AES:  ~300 MB/s")
        print("  AES-NI: ~3,000 MB/s")

# Executar
TripleDES.modes()
TripleDES.security_analysis()
TripleDES.performance_comparison()
```

***

### 📊 **DES vs AES**

#### **Comparação Detalhada**

```yaml
Comparação DES vs AES:

  🔐 Tamanho do Bloco:
    DES: 64 bits (limitante)
    AES: 128 bits (moderno)

  🔑 Tamanho da Chave:
    DES: 56 bits (quebrado)
    AES: 128/192/256 bits (seguro)

  ⚙️ Estrutura:
    DES: Rede de Feistel
    AES: SPN (Substitution-Permutation Network)

  🚀 Performance (software):
    DES: 50 MB/s
    AES: 300 MB/s
    AES-NI: 3,000 MB/s

  🛡️ Segurança:
    DES: Quebrado (1999)
    3DES: Fragilizado (Sweet32)
    AES: Seguro

  📜 Status:
    DES: Retirado (2005)
    3DES: Depreciado (2023)
    AES: Padrão atual
```

#### **Tabela de Transição**

| Ano  | Evento            | Impacto               |
| ---- | ----------------- | --------------------- |
| 1977 | DES adotado       | Padrão global         |
| 1998 | Deep Crack        | 56 horas para quebrar |
| 2000 | AES selecionado   | Início da transição   |
| 2005 | DES retirado      | Fim do padrão         |
| 2010 | Migração para AES | Maioria dos sistemas  |
| 2023 | 3DES depreciado   | Fim da era DES        |

***

### 🛡️ **Boas Práticas e Migração**

#### **Checklist para Migração**

```yaml
Migração de DES para AES:

  ✅ Avaliação:
    - Identificar sistemas usando DES/3DES
    - Mapear dependências de hardware
    - Documentar requisitos de compatibilidade

  ✅ Planejamento:
    - Definir cronograma de migração
    - Alocar recursos para recertificação
    - Preparar rollback plan

  ✅ Implementação:
    - Substituir por AES-256-GCM
    - Atualizar key management
    - Implementar rotação de chaves

  ✅ Validação:
    - Testar performance pós-migração
    - Validar compatibilidade
    - Certificar conformidade

  ✅ Descomissionamento:
    - Remover DES/3DES dos sistemas
    - Arquivar chaves antigas
    - Documentar sunset
```

#### **Alternativas Modernas**

```python
#!/usr/bin/env python3
# des_migration.py - Alternativas modernas ao DES

class DESMigration:
    """Alternativas modernas ao DES/3DES"""
    
    @staticmethod
    def recommendations():
        """Recomendações de migração"""
        print("Recomendações de Migração")
        print("=" * 60)
        
        recommendations = {
            "Dados em trânsito": {
                "protocolo": "TLS 1.3",
                "cipher": "AES-256-GCM",
                "key_exchange": "ECDHE"
            },
            "Dados em repouso": {
                "algoritmo": "AES-256-GCM",
                "key_size": "256 bits",
                "mode": "Authenticated encryption"
            },
            "Backward compatibility": {
                "solução": "Middleware de tradução",
                "implementação": "Proxy de decodificação",
                "risco": "Elevado - descontinuar ASAP"
            }
        }
        
        for use_case, solution in recommendations.items():
            print(f"\n{use_case}:")
            for key, value in solution.items():
                print(f"  {key}: {value}")

# Executar
DESMigration.recommendations()
```

***

### 📋 **Checklists de Segurança**

#### **Checklist para Administradores**

* [ ] Identificar todos os sistemas usando DES/3DES
* [ ] Priorizar migração para AES-256
* [ ] Desabilitar DES em configurações de TLS
* [ ] Remover 3DES de cipher suites
* [ ] Atualizar hardware criptográfico legado
* [ ] Rotacionar chaves DES remanescentes
* [ ] Documentar sunset de DES

#### **Checklist para Auditores**

* [ ] Verificar uso de DES em sistemas críticos
* [ ] Testar cipher suites (SSL/TLS)
* [ ] Auditar key management de chaves DES
* [ ] Verificar compliance com PCI-DSS (DES proibido)
* [ ] Avaliar riscos de downgrade attacks
* [ ] Validar planos de migração

***

### 📊 **Conclusão**

```yaml
DES (Data Encryption Standard):

  ❌ Status Atual:
    - Completamente quebrado
    - Não recomendado para novos sistemas
    - 3DES em sunset (2023)

  ⚠️ Riscos:
    - Brute force em horas
    - Sweet32 attack (bloco 64 bits)
    - Meet-in-the-middle

  🎯 Recomendações:
    - Migrar para AES-256-GCM
    - Desabilitar DES/3DES
    - Atualizar sistemas legados
    - Usar TLS 1.3 (sem DES/3DES)

  📈 Lições:
    - Chaves pequenas são vulneráveis
    - Tamanho do bloco importa
    - Padrões criptográficos envelhecem
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/criptografia/simetrica/des-data-encryption-standard.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
