# ASCII

### 📋 **Índice**

1. Fundamentos do ASCII
2. Tabela ASCII Completa
3. Caracteres de Controle
4. Codificação e Decodificação
5. ASCII em Programação
6. ASCII vs Unicode
7. Aplicações em Pentesting
8. Ferramentas e Conversão

***

### 🔍 **Fundamentos do ASCII**

#### **O que é ASCII?**

**ASCII (American Standard Code for Information Interchange)** é um padrão de codificação de caracteres que atribui números de 0 a 127 para representar letras, dígitos, sinais de pontuação e caracteres de controle. Desenvolvido na década de 1960, o ASCII é a base para a representação de texto em computadores e sistemas digitais.

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

```yaml
Características do ASCII:
  ✅ 7 bits por caractere (128 caracteres no total)
  ✅ Compatível universalmente
  ✅ Inclui letras maiúsculas e minúsculas (A-Z, a-z)
  ✅ Inclui dígitos numéricos (0-9)
  ✅ Inclui símbolos de pontuação comuns
  ✅ Inclui 33 caracteres de controle não imprimíveis
  ✅ Tamanho fixo (1 byte com bit mais significativo zero)

Limitações:
  ❌ Não suporta caracteres acentuados
  ❌ Não suporta caracteres não latinos (cirílico, árabe, chinês)
  ❌ Não suporta emojis ou símbolos especiais
  ❌ Limitado a 128 caracteres
```

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

```yaml
Evolução do ASCII:
  1960: Trabalhos iniciais no padrão de codificação
  1963: Primeira versão do ASCII publicada
  1967: Versão atualizada com letras minúsculas
  1968: Adoção pelo Departamento de Defesa dos EUA
  1970s: Tornou-se padrão em sistemas computacionais
  1980s: Expansão para 8 bits (ASCII estendido)
  1990s: Unicode começa a suplantar ASCII
  2020s: ASCII ainda fundamental em protocolos de rede
```

#### **Estrutura do ASCII**

```python
#!/usr/bin/env python3
# ascii_structure.py

class ASCIIStructure:
    """Estrutura e organização do padrão ASCII"""
    
    # Categorias ASCII
    CATEGORIES = {
        'control': range(0, 32),      # Caracteres de controle (0-31)
        'printable': range(32, 127),  # Caracteres imprimíveis (32-126)
        'delete': 127                  # DEL (127)
    }
    
    # Subcategorias de caracteres imprimíveis
    PRINTABLE_SUBCATEGORIES = {
        'space': 32,                    # Espaço
        'punctuation': range(33, 48),   # Pontuação !"#$%&'()*+,-./
        'digits': range(48, 58),        # Dígitos 0-9
        'punctuation2': range(58, 65),  # Pontuação :;<=>?@
        'uppercase': range(65, 91),     # Letras maiúsculas A-Z
        'punctuation3': range(91, 97),  # Pontuação [\]^_`
        'lowercase': range(97, 123),    # Letras minúsculas a-z
        'punctuation4': range(123, 127) # Pontuação {|}~
    }
    
    @classmethod
    def get_category(cls, code):
        """Obter categoria de um código ASCII"""
        if code in cls.CATEGORIES['control']:
            return 'control'
        elif code == 127:
            return 'delete'
        elif 32 <= code <= 126:
            return 'printable'
        return 'unknown'
    
    @classmethod
    def get_subcategory(cls, code):
        """Obter subcategoria de caractere imprimível"""
        for subcat, range_val in cls.PRINTABLE_SUBCATEGORIES.items():
            if isinstance(range_val, int):
                if code == range_val:
                    return subcat
            elif code in range_val:
                return subcat
        return 'unknown'

# Exemplo
ascii_struct = ASCIIStructure()
for code in [65, 97, 48, 32, 127]:
    print(f"Código {code}: {chr(code)} -> {ascii_struct.get_category(code)}")
```

***

### 📊 **Tabela ASCII Completa**

#### **Tabela de 0 a 127**

```python
#!/usr/bin/env python3
# ascii_table.py

class ASCIITable:
    """Tabela ASCII completa de 0 a 127"""
    
    @staticmethod
    def display_table():
        """Exibir tabela ASCII formatada"""
        print("=" * 80)
        print("TABELA ASCII (0-127)")
        print("=" * 80)
        print(f"{'Dec':>4} {'Hex':>4} {'Char':>5} |", end="")
        print(f"{'Dec':>4} {'Hex':>4} {'Char':>5} |", end="")
        print(f"{'Dec':>4} {'Hex':>4} {'Char':>5} |", end="")
        print(f"{'Dec':>4} {'Hex':>4} {'Char':>5}")
        print("-" * 80)
        
        for i in range(0, 128, 4):
            row = []
            for j in range(4):
                code = i + j
                if code < 128:
                    hex_val = f"{code:02X}"
                    char = ASCIITable._get_char_repr(code)
                    row.append(f"{code:>4} {hex_val:>3} {char:>5}")
                else:
                    row.append(" " * 16)
            
            print(" |".join(row))
        print("=" * 80)
    
    @staticmethod
    def _get_char_repr(code):
        """Representação do caractere (ou nome se controle)"""
        if code < 32 or code == 127:
            # Caracteres de controle
            control_names = {
                0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT',
                5: 'ENQ', 6: 'ACK', 7: 'BEL', 8: 'BS', 9: 'TAB',
                10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO',
                15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3',
                20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN',
                25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS',
                30: 'RS', 31: 'US', 127: 'DEL'
            }
            return control_names.get(code, f'CTRL-{code}')
        else:
            return f" '{chr(code)}' "
    
    @staticmethod
    def get_binary(code):
        """Obter representação binária de 7 bits"""
        return f"{code:07b}"
    
    @staticmethod
    def get_hex(code):
        """Obter representação hexadecimal"""
        return f"{code:02X}"

# Exibir tabela
ASCIITable.display_table()
```

#### **Tabela Resumida por Categoria**

```python
def display_categorized_table():
    """Exibir tabela ASCII por categoria"""
    
    categories = {
        'Controle (00-1F)': range(0, 32),
        'Espaço e Pontuação': [32] + list(range(33, 48)) + list(range(58, 65)) + list(range(91, 97)) + list(range(123, 127)),
        'Dígitos (30-39)': range(48, 58),
        'Maiúsculas (41-5A)': range(65, 91),
        'Minúsculas (61-7A)': range(97, 123),
        'Delete (7F)': [127]
    }
    
    print("=" * 60)
    print("TABELA ASCII POR CATEGORIA")
    print("=" * 60)
    
    for category, codes in categories.items():
        print(f"\n[{category}]")
        row = []
        for code in codes:
            char = chr(code) if 32 <= code <= 126 else f'[{code:02X}]'
            row.append(f"{code:3d}:{char}")
            if len(row) == 10:
                print("  ".join(row))
                row = []
        if row:
            print("  ".join(row))

display_categorized_table()
```

***

### 🎛️ **Caracteres de Controle**

#### **Caracteres de Controle ASCII (0-31 e 127)**

| Código | Abrev. | Nome                | Descrição                   | Uso Comum                     |
| ------ | ------ | ------------------- | --------------------------- | ----------------------------- |
| 0      | NUL    | Null                | Caractere nulo              | Terminação de strings em C    |
| 1      | SOH    | Start of Heading    | Início de cabeçalho         | Protocolos de comunicação     |
| 2      | STX    | Start of Text       | Início de texto             | Protocolos de comunicação     |
| 3      | ETX    | End of Text         | Fim de texto                | Protocolos de comunicação     |
| 4      | EOT    | End of Transmission | Fim de transmissão          | Protocolos de comunicação     |
| 5      | ENQ    | Enquiry             | Consulta                    | Protocolos de comunicação     |
| 6      | ACK    | Acknowledge         | Confirmação                 | Protocolos de comunicação     |
| 7      | BEL    | Bell                | Campainha                   | Alertas sonoros               |
| 8      | BS     | Backspace           | Retrocesso                  | Edição de texto               |
| 9      | TAB    | Horizontal Tab      | Tabulação horizontal        | Formatação de texto           |
| 10     | LF     | Line Feed           | Nova linha                  | Quebra de linha (Unix)        |
| 11     | VT     | Vertical Tab        | Tabulação vertical          | Formatação de texto           |
| 12     | FF     | Form Feed           | Alimentação de página       | Impressão                     |
| 13     | CR     | Carriage Return     | Retorno de carro            | Quebra de linha (Windows/Mac) |
| 14     | SO     | Shift Out           | Shift out                   | Seleção de caracteres         |
| 15     | SI     | Shift In            | Shift in                    | Seleção de caracteres         |
| 16     | DLE    | Data Link Escape    | Escape de enlace            | Controle de comunicação       |
| 17     | DC1    | Device Control 1    | Controle de dispositivo 1   | Controle de hardware (XON)    |
| 18     | DC2    | Device Control 2    | Controle de dispositivo 2   | Controle de hardware          |
| 19     | DC3    | Device Control 3    | Controle de dispositivo 3   | Controle de hardware (XOFF)   |
| 20     | DC4    | Device Control 4    | Controle de dispositivo 4   | Controle de hardware          |
| 21     | NAK    | Negative Ack.       | Confirmação negativa        | Protocolos de comunicação     |
| 22     | SYN    | Synchronous Idle    | Idle síncrono               | Sincronização                 |
| 23     | ETB    | End of Trans. Block | Fim de bloco de transmissão | Protocolos de comunicação     |
| 24     | CAN    | Cancel              | Cancelar                    | Cancelamento                  |
| 25     | EM     | End of Medium       | Fim de mídia                | Fim de fita/mídia             |
| 26     | SUB    | Substitute          | Substituir                  | Substituição de caractere     |
| 27     | ESC    | Escape              | Escape                      | Comandos de escape            |
| 28     | FS     | File Separator      | Separador de arquivo        | Estrutura de dados            |
| 29     | GS     | Group Separator     | Separador de grupo          | Estrutura de dados            |
| 30     | RS     | Record Separator    | Separador de registro       | Estrutura de dados            |
| 31     | US     | Unit Separator      | Separador de unidade        | Estrutura de dados            |
| 127    | DEL    | Delete              | Delete                      | Remoção                       |

```python
#!/usr/bin/env python3
# control_chars.py

class ControlCharacters:
    """Manipulação de caracteres de controle ASCII"""
    
    CONTROL_NAMES = {
        0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT',
        5: 'ENQ', 6: 'ACK', 7: 'BEL', 8: 'BS', 9: 'TAB',
        10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO',
        15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3',
        20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN',
        25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS',
        30: 'RS', 31: 'US', 127: 'DEL'
    }
    
    @classmethod
    def is_control(cls, char):
        """Verificar se caractere é de controle"""
        code = ord(char)
        return code < 32 or code == 127
    
    @classmethod
    def get_control_name(cls, code):
        """Obter nome do caractere de controle"""
        return cls.CONTROL_NAMES.get(code, f'UNKNOWN_{code}')
    
    @classmethod
    def escape_control(cls, text):
        """Escapar caracteres de controle para visualização"""
        result = []
        for char in text:
            code = ord(char)
            if code < 32 or code == 127:
                result.append(f'<{cls.get_control_name(code)}>')
            else:
                result.append(char)
        return ''.join(result)
    
    @classmethod
    def generate_control_sequence(cls, start, end):
        """Gerar sequência de caracteres de controle"""
        return bytes(range(start, end + 1))

# Exemplo
control = ControlCharacters()
test_text = "Hello\x07World\x0AEnd"
print(f"Original: {test_text}")
print(f"Escapado: {control.escape_control(test_text)}")
```

***

### 🔧 **Codificação e Decodificação**

#### **Conversão Básica**

```python
#!/usr/bin/env python3
# ascii_convert.py

class ASCIIConverter:
    """Conversões entre diferentes representações ASCII"""
    
    @staticmethod
    def char_to_code(char):
        """Caractere para código ASCII"""
        return ord(char)
    
    @staticmethod
    def code_to_char(code):
        """Código ASCII para caractere"""
        if 0 <= code <= 127:
            return chr(code)
        raise ValueError(f"Código {code} fora do intervalo ASCII (0-127)")
    
    @staticmethod
    def string_to_codes(text):
        """String para lista de códigos ASCII"""
        return [ord(c) for c in text]
    
    @staticmethod
    def codes_to_string(codes):
        """Lista de códigos para string"""
        return ''.join(chr(c) for c in codes)
    
    @staticmethod
    def to_binary(text):
        """String para representação binária"""
        return ' '.join(f"{ord(c):07b}" for c in text)
    
    @staticmethod
    def from_binary(binary_str):
        """Binário para string"""
        codes = [int(b, 2) for b in binary_str.split()]
        return ''.join(chr(c) for c in codes)
    
    @staticmethod
    def to_hex(text, separator=' '):
        """String para representação hexadecimal"""
        return separator.join(f"{ord(c):02X}" for c in text)
    
    @staticmethod
    def from_hex(hex_str):
        """Hexadecimal para string"""
        hex_bytes = hex_str.replace(' ', '')
        codes = [int(hex_bytes[i:i+2], 16) for i in range(0, len(hex_bytes), 2)]
        return ''.join(chr(c) for c in codes)
    
    @staticmethod
    def to_octal(text, separator=' '):
        """String para representação octal"""
        return separator.join(f"{ord(c):03o}" for c in text)
    
    @staticmethod
    def to_decimal(text, separator=' '):
        """String para representação decimal"""
        return separator.join(str(ord(c)) for c in text)

# Exemplo
converter = ASCIIConverter()
text = "Hello World!"

print(f"Texto: {text}")
print(f"Códigos: {converter.string_to_codes(text)}")
print(f"Binário: {converter.to_binary(text)}")
print(f"Hexadecimal: {converter.to_hex(text)}")
print(f"Octal: {converter.to_octal(text)}")
print(f"Decimal: {converter.to_decimal(text)}")
```

#### **Codificação Avançada**

```python
#!/usr/bin/env python3
# ascii_advanced.py

import base64
import binascii

class ASCIIAdvanced:
    """Técnicas avançadas de codificação ASCII"""
    
    @staticmethod
    def xor_encrypt(text, key):
        """Criptografia XOR com chave ASCII"""
        result = []
        for i, char in enumerate(text):
            key_char = key[i % len(key)]
            result.append(chr(ord(char) ^ ord(key_char)))
        return ''.join(result)
    
    @staticmethod
    def caesar_cipher(text, shift):
        """Cifra de César (apenas letras ASCII)"""
        result = []
        for char in text:
            if 'A' <= char <= 'Z':
                result.append(chr((ord(char) - ord('A') + shift) % 26 + ord('A')))
            elif 'a' <= char <= 'z':
                result.append(chr((ord(char) - ord('a') + shift) % 26 + ord('a')))
            else:
                result.append(char)
        return ''.join(result)
    
    @staticmethod
    def atbash_cipher(text):
        """Cifra Atbash (A<->Z, B<->Y, etc.)"""
        result = []
        for char in text:
            if 'A' <= char <= 'Z':
                result.append(chr(ord('Z') - (ord(char) - ord('A'))))
            elif 'a' <= char <= 'z':
                result.append(chr(ord('z') - (ord(char) - ord('a'))))
            else:
                result.append(char)
        return ''.join(result)
    
    @staticmethod
    def rot13(text):
        """ROT13 (Cifra de César com shift 13)"""
        return ASCIIAdvanced.caesar_cipher(text, 13)
    
    @staticmethod
    def base64_encode(text):
        """Codificar para Base64"""
        return base64.b64encode(text.encode()).decode()
    
    @staticmethod
    def base64_decode(encoded):
        """Decodificar de Base64"""
        return base64.b64decode(encoded.encode()).decode()
    
    @staticmethod
    def hex_encode(text):
        """Codificar para hexadecimal"""
        return text.encode().hex()
    
    @staticmethod
    def hex_decode(hex_str):
        """Decodificar de hexadecimal"""
        return bytes.fromhex(hex_str).decode()
    
    @staticmethod
    def url_encode(text):
        """URL encoding (%XX)"""
        import urllib.parse
        return urllib.parse.quote(text)
    
    @staticmethod
    def url_decode(encoded):
        """URL decoding"""
        import urllib.parse
        return urllib.parse.unquote(encoded)

# Exemplo
advanced = ASCIIAdvanced()
text = "Hello World!"

print(f"Original: {text}")
print(f"ROT13: {advanced.rot13(text)}")
print(f"Atbash: {advanced.atbash_cipher(text)}")
print(f"Base64: {advanced.base64_encode(text)}")
print(f"Hex: {advanced.hex_encode(text)}")
print(f"URL: {advanced.url_encode(text)}")
```

***

### 💻 **ASCII em Programação**

#### **Python**

```python
#!/usr/bin/env python3
# ascii_python.py

class ASCIIPython:
    """Manipulação de ASCII em Python"""
    
    @staticmethod
    def basic_operations():
        """Operações básicas com ASCII"""
        # Caractere para código
        print(f"'A' -> {ord('A')}")
        print(f"'a' -> {ord('a')}")
        print(f"'0' -> {ord('0')}")
        
        # Código para caractere
        print(f"65 -> '{chr(65)}'")
        print(f"97 -> '{chr(97)}'")
        print(f"48 -> '{chr(48)}'")
    
    @staticmethod
    def string_validation(text):
        """Validar se string contém apenas ASCII"""
        return all(ord(c) < 128 for c in text)
    
    @staticmethod
    def filter_ascii(text):
        """Filtrar apenas caracteres ASCII"""
        return ''.join(c for c in text if ord(c) < 128)
    
    @staticmethod
    def to_ascii_escape(text):
        """Converter para sequências de escape ASCII"""
        result = []
        for c in text:
            code = ord(c)
            if code < 32 or code == 127:
                result.append(f'\\x{code:02x}')
            elif code == 92:  # Backslash
                result.append('\\\\')
            elif 32 <= code <= 126:
                result.append(c)
            else:
                result.append(f'\\u{code:04x}')
        return ''.join(result)
    
    @staticmethod
    def generate_ascii_art(char, width=10, height=5):
        """Gerar arte ASCII simples"""
        for _ in range(height):
            print(char * width)

# Exemplo
ascii_py = ASCIIPython()
ascii_py.basic_operations()

text = "Hello 世界!"
print(f"Original: {text}")
print(f"É ASCII? {ascii_py.string_validation(text)}")
print(f"ASCII filtrado: {ascii_py.filter_ascii(text)}")
print(f"ASCII escape: {ascii_py.to_ascii_escape(text)}")
```

#### **C/C++**

```c
// ascii_c.c
#include <stdio.h>
#include <ctype.h>
#include <string.h>

// Verificar se caractere é ASCII
int is_ascii(char c) {
    return (unsigned char)c < 128;
}

// Converter string para maiúsculas (apenas ASCII)
void to_upper_ascii(char* str) {
    for (int i = 0; str[i]; i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            str[i] = str[i] - 'a' + 'A';
        }
    }
}

// Contar caracteres ASCII imprimíveis
int count_printable(const char* str) {
    int count = 0;
    for (int i = 0; str[i]; i++) {
        if (str[i] >= 32 && str[i] <= 126) {
            count++;
        }
    }
    return count;
}

// Exibir tabela ASCII
void print_ascii_table() {
    printf("ASCII Table (32-126)\n");
    printf("====================\n");
    for (int i = 32; i <= 126; i++) {
        printf("%3d: '%c'   ", i, i);
        if ((i - 31) % 5 == 0) printf("\n");
    }
    printf("\n");
}

int main() {
    char text[] = "Hello World!";
    
    printf("Texto: %s\n", text);
    printf("ASCII? %d\n", is_ascii(text[0]));
    
    to_upper_ascii(text);
    printf("Maiúsculas: %s\n", text);
    
    printf("Caracteres imprimíveis: %d\n", count_printable(text));
    print_ascii_table();
    
    return 0;
}
```

#### **JavaScript/Node.js**

```javascript
// ascii_js.js

// Caractere para código ASCII
function charToCode(char) {
    return char.charCodeAt(0);
}

// Código para caractere
function codeToChar(code) {
    return String.fromCharCode(code);
}

// Validar string ASCII
function isASCII(str) {
    return /^[\x00-\x7F]*$/.test(str);
}

// Converter para ASCII escape
function toAsciiEscape(str) {
    return str.split('').map(c => {
        const code = c.charCodeAt(0);
        if (code < 32 || code === 127) {
            return `\\x${code.toString(16).padStart(2, '0')}`;
        }
        if (code === 92) return '\\\\';
        if (code >= 32 && code <= 126) return c;
        return `\\u${code.toString(16).padStart(4, '0')}`;
    }).join('');
}

// Gerador de arte ASCII
function asciiArt(char, width, height) {
    for (let i = 0; i < height; i++) {
        console.log(char.repeat(width));
    }
}

// Exemplo
const text = "Hello World!";
console.log(`Texto: ${text}`);
console.log(`'A' -> ${charToCode('A')}`);
console.log(`65 -> '${codeToChar(65)}'`);
console.log(`É ASCII? ${isASCII(text)}`);
console.log(`ASCII escape: ${toAsciiEscape(text)}`);
asciiArt('*', 20, 5);
```

***

### 🌐 **ASCII vs Unicode**

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

```python
#!/usr/bin/env python3
# ascii_vs_unicode.py

class ASCIIvsUnicode:
    """Comparação entre ASCII e Unicode"""
    
    @staticmethod
    def compare():
        """Comparar características de ASCII e Unicode"""
        
        print("=" * 70)
        print("ASCII vs UNICODE - COMPARAÇÃO")
        print("=" * 70)
        
        comparisons = [
            ("Tamanho", "7 bits (128 caracteres)", "Variável (1-4 bytes)", "Unicode maior"),
            ("Caracteres", "Inglês básico", "Todos os idiomas", "Unicode suporta mais"),
            ("Emojis", "❌", "✅", "Apenas Unicode"),
            ("Acentuação", "❌", "✅", "Apenas Unicode"),
            ("Compatibilidade", "Universal", "Ampla", "Ambos amplamente suportados"),
            ("Memória", "1 byte por char", "1-4 bytes", "ASCII mais eficiente"),
            ("Velocidade", "Muito rápida", "Rápida", "ASCII mais rápido"),
        ]
        
        print(f"{'Característica':<20} {'ASCII':<25} {'Unicode':<25} {'Vencedor':<15}")
        print("-" * 85)
        
        for feat, ascii_desc, unicode_desc, winner in comparisons:
            print(f"{feat:<20} {ascii_desc:<25} {unicode_desc:<25} {winner:<15}")
        
        print("=" * 70)
    
    @staticmethod
    def encoding_demo():
        """Demonstração de diferentes encodings"""
        text = "Olá, 世界! 👋"
        
        encodings = ['ascii', 'utf-8', 'utf-16', 'latin1']
        
        print("\nDEMONSTRAÇÃO DE ENCODINGS")
        print("=" * 50)
        
        for encoding in encodings:
            try:
                encoded = text.encode(encoding)
                print(f"{encoding:8}: {encoded.hex()}")
                print(f"         Tamanho: {len(encoded)} bytes")
            except UnicodeEncodeError as e:
                print(f"{encoding:8}: ERRO - {e}")
        
        print("=" * 50)

# Executar comparação
ASCIIvsUnicode.compare()
ASCIIvsUnicode.encoding_demo()
```

#### **ASCII Estendido (ISO-8859-1 / Latin1)**

```python
#!/usr/bin/env python3
# extended_ascii.py

class ExtendedASCII:
    """ASCII Estendido (ISO-8859-1 / Latin1)"""
    
    # Caracteres especiais do Latin1 (128-255)
    LATIN1_SPECIAL = {
        0xC0: 'À', 0xC1: 'Á', 0xC2: 'Â', 0xC3: 'Ã', 0xC4: 'Ä',
        0xC5: 'Å', 0xC6: 'Æ', 0xC7: 'Ç', 0xC8: 'È', 0xC9: 'É',
        0xCA: 'Ê', 0xCB: 'Ë', 0xCC: 'Ì', 0xCD: 'Í', 0xCE: 'Î',
        0xCF: 'Ï', 0xD0: 'Ð', 0xD1: 'Ñ', 0xD2: 'Ò', 0xD3: 'Ó',
        0xD4: 'Ô', 0xD5: 'Õ', 0xD6: 'Ö', 0xD8: 'Ø', 0xD9: 'Ù',
        0xDA: 'Ú', 0xDB: 'Û', 0xDC: 'Ü', 0xDD: 'Ý', 0xDE: 'Þ',
        0xDF: 'ß', 0xE0: 'à', 0xE1: 'á', 0xE2: 'â', 0xE3: 'ã',
        0xE4: 'ä', 0xE5: 'å', 0xE6: 'æ', 0xE7: 'ç', 0xE8: 'è',
        0xE9: 'é', 0xEA: 'ê', 0xEB: 'ë', 0xEC: 'ì', 0xED: 'í',
        0xEE: 'î', 0xEF: 'ï', 0xF0: 'ð', 0xF1: 'ñ', 0xF2: 'ò',
        0xF3: 'ó', 0xF4: 'ô', 0xF5: 'õ', 0xF6: 'ö', 0xF8: 'ø',
        0xF9: 'ù', 0xFA: 'ú', 0xFB: 'û', 0xFC: 'ü', 0xFD: 'ý',
        0xFE: 'þ', 0xFF: 'ÿ'
    }
    
    @classmethod
    def is_latin1_extended(cls, code):
        """Verificar se código pertence ao Latin1 estendido"""
        return 128 <= code <= 255
    
    @classmethod
    def get_latin1_char(cls, code):
        """Obter caractere Latin1 para código"""
        if code in cls.LATIN1_SPECIAL:
            return cls.LATIN1_SPECIAL[code]
        return chr(code) if 32 <= code <= 126 else f'<{code:02X}>'
    
    @classmethod
    def display_latin1_table(cls):
        """Exibir tabela Latin1 (128-255)"""
        print("=" * 80)
        print("ASCII ESTENDIDO - Latin1 (ISO-8859-1)")
        print("=" * 80)
        
        for i in range(128, 256, 8):
            row = []
            for j in range(8):
                code = i + j
                char = cls.get_latin1_char(code)
                row.append(f"{code:3d}:{char}")
            print("  ".join(row))
        
        print("=" * 80)

# Exibir tabela Latin1
ExtendedASCII.display_latin1_table()
```

***

### 🎯 **Aplicações em Pentesting**

#### **ASCII em Payloads e Bypass**

```python
#!/usr/bin/env python3
# ascii_pentest.py

class ASCIITechniques:
    """Técnicas de ASCII em pentesting"""
    
    @staticmethod
    def ascii_encoding_bypass(payload):
        """Bypass de WAF usando encoding ASCII"""
        # Converter para códigos ASCII
        encoded = ''.join(f'&#{ord(c)};' for c in payload)
        return encoded
    
    @staticmethod
    def hex_encoding_bypass(payload):
        """Bypass usando encoding hexadecimal"""
        return ''.join(f'%{ord(c):02x}' for c in payload)
    
    @staticmethod
    def octal_encoding_bypass(payload):
        """Bypass usando encoding octal"""
        return ''.join(f'\\{ord(c):03o}' for c in payload)
    
    @staticmethod
    def mixed_case_bypass(payload):
        """Bypass usando variação de maiúsculas/minúsculas"""
        import random
        result = []
        for c in payload:
            if c.isalpha():
                if random.choice([True, False]):
                    result.append(c.upper())
                else:
                    result.append(c.lower())
            else:
                result.append(c)
        return ''.join(result)
    
    @staticmethod
    def null_byte_injection(payload):
        """Injeção de byte nulo (para bypass em C)"""
        return payload + '\x00'
    
    @staticmethod
    def carriage_return_bypass(payload):
        """Bypass usando carriage return"""
        return payload + '\r'
    
    @staticmethod
    def tab_encoding_bypass(payload):
        """Bypass usando tabulação"""
        return payload.replace(' ', '\t')
    
    @staticmethod
    def generate_sql_payloads():
        """Gerar payloads SQL com encoding ASCII"""
        sql_payloads = [
            ("SELECT", "SELECT"),
            ("UNION", "UNION"),
            ("' OR '1'='1", "' OR '1'='1"),
            ("1=1--", "1=1--"),
        ]
        
        print("SQL Injection Payloads com Encoding ASCII")
        print("=" * 60)
        
        for original, payload in sql_payloads:
            hex_enc = ASCIITechniques.hex_encoding_bypass(payload)
            print(f"{original}:")
            print(f"  Hex: {hex_enc}")
            print(f"  Decimal: {ASCIITechniques.ascii_encoding_bypass(payload)}")
            print()

# Exemplo
ascii_tech = ASCIITechniques()
payload = "<script>alert('XSS')</script>"

print(f"Payload original: {payload}")
print(f"Hex encoding: {ascii_tech.hex_encoding_bypass(payload)}")
print(f"Octal encoding: {ascii_tech.octal_encoding_bypass(payload)}")
print(f"Decimal encoding: {ascii_tech.ascii_encoding_bypass(payload)}")
print(f"Mixed case: {ascii_tech.mixed_case_bypass(payload)}")

ascii_tech.generate_sql_payloads()
```

#### **Análise de Tráfego e Logs**

```python
#!/usr/bin/env python3
# ascii_analysis.py

class ASCIIAnalysis:
    """Análise de tráfego e logs com ASCII"""
    
    @staticmethod
    def detect_non_ascii(data):
        """Detectar caracteres não-ASCII em dados"""
        non_ascii = []
        for i, byte in enumerate(data):
            if isinstance(byte, str):
                code = ord(byte)
            else:
                code = byte
            
            if code >= 128:
                non_ascii.append((i, code, hex(code)))
        
        return non_ascii
    
    @staticmethod
    def extract_printable(data):
        """Extrair caracteres ASCII imprimíveis"""
        if isinstance(data, bytes):
            data = data.decode('latin1')
        
        return ''.join(c for c in data if 32 <= ord(c) <= 126)
    
    @staticmethod
    def analyze_binary(binary_data):
        """Analisar dados binários para ASCII legível"""
        printable = ASCIIAnalysis.extract_printable(binary_data)
        non_ascii = ASCIIAnalysis.detect_non_ascii(binary_data)
        
        print(f"Tamanho: {len(binary_data)} bytes")
        print(f"Caracteres ASCII imprimíveis: {len(printable)}")
        print(f"Caracteres não-ASCII: {len(non_ascii)}")
        
        if printable:
            print(f"Strings legíveis: {printable[:200]}")
        
        return printable
    
    @staticmethod
    def strings_like(filepath, min_length=4):
        """Emular comando 'strings' (extrair sequências ASCII)"""
        import subprocess
        
        try:
            result = subprocess.run(['strings', '-n', str(min_length), filepath],
                                   capture_output=True, text=True)
            return result.stdout.split('\n')
        except:
            # Implementação fallback em Python
            with open(filepath, 'rb') as f:
                data = f.read()
            
            strings = []
            current = []
            
            for byte in data:
                if 32 <= byte <= 126:
                    current.append(chr(byte))
                else:
                    if len(current) >= min_length:
                        strings.append(''.join(current))
                    current = []
            
            if len(current) >= min_length:
                strings.append(''.join(current))
            
            return strings

# Exemplo
analyzer = ASCIIAnalysis()

# Analisar string de exemplo
test_data = b"Hello\xFFWorld\x00\x01\x02\x03\x04\x05"
print("=== Análise de Dados ===")
analyzer.analyze_binary(test_data)

# Extrair strings de arquivo (exemplo)
# strings = analyzer.strings_like('/bin/ls', 4)
# print(f"\nStrings encontradas: {len(strings)}")
```

***

### 🛠️ **Ferramentas e Conversão**

#### **Ferramentas CLI**

```bash
# Converter texto para ASCII codes
echo "Hello" | od -An -td1
echo "Hello" | hexdump -C
echo "Hello" | xxd

# Mostrar tabela ASCII
man ascii
ascii -t
ascii -d 65

# Converter entre representações
# Decimal para caractere
printf "\x48\x65\x6c\x6c\x6f\n"
python3 -c "print(chr(72))"

# String para hexadecimal
echo -n "Hello" | xxd -p
echo -n "Hello" | od -An -tx1

# Hexadecimal para string
echo "48656c6c6f" | xxd -p -r

# Base64 (baseado em ASCII)
echo -n "Hello" | base64
echo "SGVsbG8=" | base64 -d
```

#### **Script de Conversão Universal**

```python
#!/usr/bin/env python3
# ascii_converter_cli.py

import argparse
import sys

class ASCIIUniversalConverter:
    """Conversor universal de representações ASCII"""
    
    @staticmethod
    def convert(input_text, from_format, to_format):
        """Converter entre diferentes formatos"""
        
        # Decodificar entrada
        if from_format == 'text':
            data = input_text
        elif from_format == 'decimal':
            codes = [int(x) for x in input_text.split()]
            data = ''.join(chr(c) for c in codes)
        elif from_format == 'hex':
            hex_str = input_text.replace(' ', '').replace('0x', '')
            data = bytes.fromhex(hex_str).decode('latin1')
        elif from_format == 'binary':
            codes = [int(b, 2) for b in input_text.split()]
            data = ''.join(chr(c) for c in codes)
        elif from_format == 'octal':
            codes = [int(o, 8) for o in input_text.split()]
            data = ''.join(chr(c) for c in codes)
        else:
            raise ValueError(f"Formato de entrada inválido: {from_format}")
        
        # Codificar saída
        if to_format == 'text':
            return data
        elif to_format == 'decimal':
            return ' '.join(str(ord(c)) for c in data)
        elif to_format == 'hex':
            return data.encode().hex()
        elif to_format == 'binary':
            return ' '.join(f"{ord(c):07b}" for c in data)
        elif to_format == 'octal':
            return ' '.join(f"{ord(c):03o}" for c in data)
        else:
            raise ValueError(f"Formato de saída inválido: {to_format}")

# CLI
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Conversor Universal ASCII')
    parser.add_argument('-i', '--input', required=True, help='Texto de entrada')
    parser.add_argument('-f', '--from', dest='from_format', 
                       choices=['text', 'decimal', 'hex', 'binary', 'octal'],
                       default='text', help='Formato de entrada')
    parser.add_argument('-t', '--to', dest='to_format',
                       choices=['text', 'decimal', 'hex', 'binary', 'octal'],
                       default='hex', help='Formato de saída')
    
    args = parser.parse_args()
    
    try:
        result = ASCIIUniversalConverter.convert(args.input, args.from_format, args.to_format)
        print(result)
    except Exception as e:
        print(f"Erro: {e}", file=sys.stderr)
        sys.exit(1)
```

***

### 📊 **Conclusão e Boas Práticas**

#### **Resumo Técnico**

```yaml
ASCII Encoding:
  ✅ Padrão fundamental de codificação
  ✅ 128 caracteres (0-127)
  ✅ Inclui letras, dígitos, pontuação e controle
  ✅ Base para protocolos de rede

Limitações:
  ❌ Sem suporte a acentos
  ❌ Sem suporte a emojis
  ❌ Sem suporte a idiomas não latinos
  ❌ Limitado a 128 caracteres

Melhores Práticas:
  - Usar Unicode para texto internacional
  - Usar ASCII para protocolos e sistemas
  - Validar entrada/saída de caracteres
  - Tratar caracteres de controle adequadamente
```

#### **Referências**

* **ANSI X3.4-1986** - American National Standard for Information Systems
* **RFC 20** - ASCII format for Network Interchange
* **ISO/IEC 646** - 7-bit coded character set
* **Unicode Standard** - Extensão moderna do ASCII


---

# 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/encodagem-encoding/ascii.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.
