# Downgrade Attacks

## 📌 Classificação

* **Categoria:** Criptografia Assimétrica (Chave Pública)
* **Criado por:** Ron Rivest, Adi Shamir, Leonard Adleman (1977)
* **Base Matemática:** Fatoração de números primos grandes
* **Tamanhos de Chave:** 1024 (obsoleto), 2048 (padrão), 3072, 4096 bits
* **Status:** ✅ Padrão global (mas com alternativas modernas)

***

## 🎯 Descrição Geral

**RSA** é o algoritmo de criptografia assimétrica mais famoso e amplamente utilizado do mundo. Baseia-se na **dificuldade computacional de fatorar números inteiros grandes** em seus fatores primos.

```
Chave Pública  (n, e) → usado para CIFRAR
Chave Privada  (n, d) → usado para DECIFRAR

Mensagem + Chave Pública → Cifrado
Cifrado + Chave Privada → Mensagem original
```

### Analogia

> *"RSA é como uma caixa postal com duas chaves: qualquer um pode colocar uma carta (chave pública), mas só o dono pode abrir (chave privada)."*

***

## ⚙️ Como Funciona (Matemática Simplificada)

### Passo a Passo da Geração de Chaves

#### 1. Escolher dois números primos grandes

```
p = 61
q = 53
```

#### 2. Calcular n = p × q

```
n = 61 × 53 = 3233
```

`n` será usado tanto na chave pública quanto na privada.

#### 3. Calcular φ(n) = (p-1) × (q-1)

```
φ(n) = (61-1) × (53-1) = 60 × 52 = 3120
```

φ(n) é a função totiente de Euler.

#### 4. Escolher e (público)

`e` deve ser:

* 1 < e < φ(n)
* Coprimo com φ(n) (mdc(e, φ(n)) = 1)

```
e = 17 (comum)
```

#### 5. Calcular d (privado)

`d` é o inverso multiplicativo modular: `d ≡ e⁻¹ mod φ(n)`

```
d = 2753 (pois 17 × 2753 ≡ 1 mod 3120)
```

### Chaves Geradas

```
Chave Pública:  (n = 3233, e = 17)
Chave Privada: (n = 3233, d = 2753)
```

### Cifragem e Decifragem

```
Cifragem:   C = Mᵉ mod n
Decifragem: M = Cᵈ mod n

Exemplo com M = 65:
C = 65¹⁷ mod 3233 = 2790
M = 2790²⁷⁵³ mod 3233 = 65
```

***

## 🧠 Algoritmo Completo (Pseudocódigo)

```python
def gerar_chaves_rsa(tamanho=2048):
    # 1. Gerar dois primos grandes
    p = gerar_primo_grande(tamanho // 2)
    q = gerar_primo_grande(tamanho // 2)
    
    # 2. Calcular n
    n = p * q
    
    # 3. Calcular φ(n)
    phi_n = (p - 1) * (q - 1)
    
    # 4. Escolher e (65537 é comum)
    e = 65537
    
    # 5. Calcular d (inverso modular)
    d = mod_inverse(e, phi_n)
    
    return (n, e), (n, d)  # pública, privada
```

***

## 🔐 Usos do RSA

| Aplicação                         | Descrição                                             |
| --------------------------------- | ----------------------------------------------------- |
| **SSL/TLS (HTTPS)**               | Autenticação e troca de chaves simétricas             |
| **Assinaturas Digitais**          | Garantir autenticidade e integridade                  |
| **Certificados Digitais (X.509)** | Identificação de sites e entidades                    |
| **E-mail seguro (PGP/GPG)**       | Cifragem e assinatura de mensagens                    |
| **SSH**                           | Autenticação de servidores e clientes                 |
| **VPN**                           | Autenticação e troca de chaves                        |
| **Blockchain**                    | Assinatura de transações (embora ECC seja mais comum) |

***

## 💻 Exemplos Práticos

### Exemplo 1 – Gerar Chaves RSA (OpenSSL)

```bash
# Gerar chave privada RSA de 2048 bits
openssl genrsa -out private_key.pem 2048

# Extrair chave pública
openssl rsa -in private_key.pem -pubout -out public_key.pem

# Verificar conteúdo da chave privada
openssl rsa -in private_key.pem -text -noout

# Verificar conteúdo da chave pública
openssl rsa -pubin -in public_key.pem -text -noout
```

### Exemplo 2 – Cifrar/Decifrar com RSA (OpenSSL)

```bash
# Criar arquivo de mensagem
echo "Mensagem super secreta" > msg.txt

# Cifrar com chave pública
openssl rsautl -encrypt -inkey public_key.pem -pubin -in msg.txt -out msg.enc

# Decifrar com chave privada
openssl rsautl -decrypt -inkey private_key.pem -in msg.enc -out msg.dec

# Verificar
cat msg.dec
```

### Exemplo 3 – Assinatura Digital com RSA

```bash
# Assinar arquivo
openssl dgst -sha256 -sign private_key.pem -out signature.bin msg.txt

# Verificar assinatura
openssl dgst -sha256 -verify public_key.pem -signature signature.bin msg.txt
```

### Exemplo 4 – RSA em Python (Criptografia)

```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

# Gerar chaves
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

print(f"Chave Privada:\n{private_key.decode()}")
print(f"Chave Pública:\n{public_key.decode()}")

# Cifrar com chave pública
recipient_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
mensagem = b"Minha mensagem secreta"
cifrado = cipher_rsa.encrypt(mensagem)
print(f"Cifrado (hex): {binascii.hexlify(cifrado)}")

# Decifrar com chave privada
private_key_obj = RSA.import_key(private_key)
cipher_rsa = PKCS1_OAEP.new(private_key_obj)
original = cipher_rsa.decrypt(cifrado)
print(f"Original: {original.decode()}")
```

### Exemplo 5 – RSA em Python (Assinatura)

```python
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256

# Gerar chaves
key = RSA.generate(2048)

# Assinar mensagem
mensagem = b"Documento importante"
hash_obj = SHA256.new(mensagem)
signature = pkcs1_15.new(key).sign(hash_obj)
print(f"Assinatura (hex): {signature.hex()}")

# Verificar assinatura
try:
    pkcs1_15.new(key.publickey()).verify(hash_obj, signature)
    print("Assinatura VÁLIDA")
except (ValueError, TypeError):
    print("Assinatura INVÁLIDA")
```

***

## ⚠️ Vulnerabilidades e Ataques

### 1. Fatoração (Ataque mais sério)

Se um atacante conseguir fatorar `n` em `p` e `q`, a chave privada é calculada instantaneamente.

| Tamanho    | Dificuldade                | Status        |
| ---------- | -------------------------- | ------------- |
| 512 bits   | Fatorado em 1999           | ❌ Inseguro    |
| 768 bits   | Fatorado em 2009           | ❌ Inseguro    |
| 1024 bits  | Quebrável (governos)       | ⚠️ Obsoleto   |
| 2048 bits  | Seguro por enquanto        | ✅ Padrão      |
| 3072+ bits | Seguro para futuro próximo | ✅ Recomendado |

### 2. Ataques Conhecidos

| Ataque                    | Descrição                                   | Mitigação                  |
| ------------------------- | ------------------------------------------- | -------------------------- |
| **Fatoração**             | Recuperar p e q de n                        | Usar chaves ≥ 2048 bits    |
| **Wiener Attack**         | Chave privada pequena (d)                   | Garantir d > n^(1/4)       |
| **Håstad Attack**         | Mesma mensagem para múltiplos destinatários | Usar padding (OAEP)        |
| **Coppersmith Attack**    | Mensagens pequenas                          | Padding adequado           |
| **Timing Attack**         | Medir tempo de decifragem                   | Implementação constante    |
| **Bleichenbacher Attack** | Ataque ao PKCS#1 v1.5                       | Usar OAEP                  |
| **Fault Attack**          | Induzir erro no hardware                    | Verificação de integridade |

### 3. Padding Oracle Attack (CVE-2016-1494)

Ataque famoso ao PKCS#1 v1.5 (SSL/TLS antigo).

```python
# Não use PKCS#1 v1.5, use OAEP!
# Ruim:
cipher = PKCS1_v1_5.new(key)

# Bom:
cipher = PKCS1_OAEP.new(key)
```

***

## 🔒 Recomendações de Segurança

### Tamanhos de Chave

| Ano       | Mínimo    | Recomendado | Uso                       |
| --------- | --------- | ----------- | ------------------------- |
| Até 2010  | 1024 bits | 2048 bits   | ❌ Descontinuado           |
| 2015-2025 | 2048 bits | 2048 bits   | ✅ Padrão atual            |
| 2025-2030 | 2048 bits | 3072 bits   | ✅ Preferível              |
| 2030+     | 3072 bits | 4096 bits   | ✅ Preparação pós-quântica |

### Boas Práticas

```python
# ✅ Correto
key = RSA.generate(2048)
cipher = PKCS1_OAEP.new(key)
hash_algo = SHA256()

# ❌ Errado
key = RSA.generate(1024)  # muito pequeno
cipher = PKCS1_v1_5.new(key)  # padding antigo
```

### Configuração Segura (OpenSSL)

```bash
# Gerar chave segura
openssl genrsa -out private_key.pem 3072

# Verificar tamanho
openssl rsa -in private_key.pem -text -noout | grep "Private-Key"

# Configurar apenas cifras fortes no TLS
openssl ciphers -v 'HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA'
```

***

## 📊 Comparação: RSA vs ECC

| Característica            | RSA-2048  | ECC-256  |
| ------------------------- | --------- | -------- |
| **Segurança**             | 112 bits  | 128 bits |
| **Tamanho da chave**      | 2048 bits | 256 bits |
| **Tamanho da assinatura** | 256 bytes | 64 bytes |
| **Cifragem (KB/s)**       | \~500     | \~2000   |
| **Assinatura (ops/s)**    | \~200     | \~2000   |
| **Verificação (ops/s)**   | \~5000    | \~1000   |

> ECC é mais rápido para assinatura, RSA é mais rápido para verificação.

***

## 🔄 Alternativas ao RSA

| Algoritmo                | Vantagem                    | Desvantagem                |
| ------------------------ | --------------------------- | -------------------------- |
| **ECC (Ed25519)**        | Chaves menores, mais rápido | Mais novo, menos auditado  |
| **RSA**                  | Amplamente suportado        | Chaves grandes, mais lento |
| **Post-Quantum (Kyber)** | Resistente a quantum        | Muito novo                 |

***

## 📜 História

| Ano      | Evento                                    |
| -------- | ----------------------------------------- |
| **1977** | Rivest, Shamir e Adleman publicam o RSA   |
| **1983** | RSA patenteado (MIT)                      |
| **1991** | Primeira versão do PGP (usava RSA)        |
| **1999** | RSA-512 (155 dígitos) fatorado            |
| **2000** | Patente expira (torna-se domínio público) |
| **2009** | RSA-768 (232 dígitos) fatorado            |
| **2015** | NIST recomenda RSA-2048 como mínimo       |
| **2022** | RSA-2048 ainda seguro (mas monitorado)    |

***

## 🎯 Resumo Rápido

| Ponto                   | Resumo                                                  |
| ----------------------- | ------------------------------------------------------- |
| **Base**                | Fatoração de números primos                             |
| **Tamanho recomendado** | 2048 bits (hoje), 3072 bits (futuro)                    |
| **Nunca use**           | RSA-512, RSA-1024, PKCS#1 v1.5                          |
| **Sempre use**          | OAEP padding, SHA-256+                                  |
| **Principal uso**       | Assinaturas, troca de chaves (não cifrar dados grandes) |

***

## 🔗 Links Úteis

* [RFC 8017 - PKCS#1 v2.2](https://tools.ietf.org/html/rfc8017)
* [NIST SP 800-56B - RSA Key Management](https://csrc.nist.gov/publications/detail/sp/800-56b/rev-2/final)
* [Crypto++ RSA](https://www.cryptopp.com/wiki/RSA)
* [OpenSSL RSA](https://www.openssl.org/docs/man1.1.1/man3/RSA.html)


---

# 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/tecnicas/sistemas-operacionais/android/downgrade-attacks.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.
