PROJECT PYTHON SCANNER

Projetos | DEMO SCANNER

CHAVE DE ENCRITAÇAO COM PYTHON


                    /* ENCRIPTAR FICHEIROS */
#!/usr/bin/env python3
import os
import base64
import getpass
import shutil
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

# --- 1. CONFIGURAÇÃO E INPUT ---
nome_salt = "meu_salt.salt"
pasta_backup = "./backup_keys"

# Pedir extensões ao operador
entrada = input("Quais extensões procurar? (ex: .jpg .pdf): ")
extensoes_alvo = tuple(entrada.split())

# --- 2. GESTÃO DO SALT E BACKUP ---
if os.path.exists(nome_salt):
    with open(nome_salt, "rb") as f:
        salt = f.read()
else:
    salt = os.urandom(16)
    with open(nome_salt, "wb") as f:
        f.write(salt)
    
    # Criar pasta e cópia de segurança do Salt
    if not os.path.exists(pasta_backup):
        os.makedirs(pasta_backup)
    shutil.copy2(nome_salt, os.path.join(pasta_backup, "salt.bak"))
    print(f"✨ Novo Salt gerado e guardado em {pasta_backup}/salt.bak")

# --- 3. CRIAÇÃO DA CHAVE ---
password = getpass.getpass("Digite a password para encriptação: ")
password_bytes = password.encode()

kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=600000,
)

chave_final = base64.urlsafe_b64encode(kdf.derive(password_bytes))
fernet = Fernet(chave_final)

# --- 4. SELEÇÃO E FILTRO ---
# Procuramos apenas ficheiros que NÃO tenham já a nossa extensão
files = [f for f in os.listdir(".") if f.endswith(extensoes_alvo) and not f.endswith(".jony69")]

print(f"\n[INFO] Foram encontrados {len(files)} ficheiros para processar.")

# --- 5. EXECUÇÃO ---
for arquivo in files:
    try:
        with open(arquivo, "rb") as f:
            dados = f.read()
        
        dados_cifrados = fernet.encrypt(dados)
        
        with open(arquivo, "wb") as f:
            f.write(dados_cifrados)
        
        os.rename(arquivo, arquivo + ".jony69")
        print(f"[OK] {arquivo} protegido.")
    except Exception as e:
        print(f"[ERRO] Não foi possível processar {arquivo}: {e}")

print("\nConcluído!")

             /*PARA DESENCRIPTAR OS FICHEIROS*/

#!/usr/bin/env python3

import os
import base64
import getpass
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

# --- 1. LOCALIZAÇÃO DO SALT (PRINCIPAL OU BACKUP) ---
nome_salt = "meu_salt.salt"
caminho_backup = "./backup_keys/salt.bak"

if os.path.exists(nome_salt):
    caminho_usado = nome_salt
elif os.path.exists(caminho_backup):
    caminho_usado = caminho_backup
    print("⚠️ Salt principal não encontrado. A usar o backup de segurança...")
else:
    print("❌ Erro Crítico: Nenhum ficheiro de Salt encontrado. Impossível desencriptar.")
    exit()

with open(caminho_usado, "rb") as f:
    salt = f.read()

# --- 2. GERAÇÃO DA CHAVE ---
password = getpass.getpass("Digite a password para DESENCRIPTAR: ")
password_bytes = password.encode()

kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=600000,
)

chave_final = base64.urlsafe_b64encode(kdf.derive(password_bytes))
fernet = Fernet(chave_final)

# --- 3. SELEÇÃO E CONTAGEM ---
files = [f for f in os.listdir(".") if f.endswith(".jony69")]
total = len(files)

if total == 0:
    print("\nNenhum ficheiro '.jony69' encontrado nesta pasta.")
    exit()

print(f"\n[INFO] Encontrados {total} ficheiros para processar.")

# --- 4. CICLO DE RECUPERAÇÃO COM CONTADOR ---
for i, arquivo in enumerate(files, 1):
    nome_original = arquivo.removesuffix(".jony69")
    print(f"[{i}/{total}] A processar: {arquivo}...", end=" ")

    try:
        # Ler dados encriptados
        with open(arquivo, "rb") as f:
            dados_cifrados = f.read()
        
        # Desencriptar
        dados_originais = fernet.decrypt(dados_cifrados)
        
        # Gravar o original
        with open(nome_original, "wb") as f:
            f.write(dados_originais)
        
        # Só removemos o protegido se a gravação do original teve sucesso
        os.remove(arquivo)
        print("V Sucesso!")
        
    except InvalidToken:
        print("X ERRO: Password incorreta.")
    except Exception as e:
        print(f"X ERRO CRÍTICO: {e}")

print("\nProcedimento concluído.")


                

DOCS 1

SETUP 2

PROJETO 2


                    /* FIQUE MILIONARIO COM ESTE PROGRAMA */
#!/bin/python3
import random



#def euro_calc():
        #randint(a ,b)
        #print(random.randint(1, 50))
        #print("lets shuffle those numbers :")
        #items =[1, 50]
        #print(random.choice(items))



#euro_calc()

print("the 5 numbers for the euromilhoes are: ")

i = 1
while  i <=5:
        print(random.randint(1, 50))
        i += 1

print("the 2 star numbers are : ")

star = 1
while star <=2:
        print(random.randint(1, 13))
        star += 1

print("good luck !!")


                

DOCS 2

SETUP 2

PROJETO 3


                    /* PYTHON PORT SCANNER */
#!/bin/python3
import nmap
import time
import sys

nmScan = nmap.PortScanner()

while True:
    print("\n" + "="*50)
    target_host = input("🌐 Enter target to scan (IP/Domain): ")
    
    # Pedir o range de forma organizada
    port_start = input("🔢 Enter port start: ")
    port_end = input("🔢 Enter port end: ")
    port_range = f"{port_start}-{port_end}"
    
    print("-" * 50)
    print(f"🛰️  Target: {target_host}")
    print(f"📊 Range: {port_range}")
    print(f"⏰ Starting scan at: {time.ctime()}")
    print("-" * 50)

    # Pequena animação
    print("🚦 Scan in progress", end="", flush=True)
    for _ in range(3):
        time.sleep(1)
        print("🚦", end="", flush=True)
    print("\n" + "✅ Done!" + "\n")

    # Executar o scan
    nmScan.scan(target_host, port_range)

    # Mostrar resultados
    for host in nmScan.all_hosts():
        print(f"🏠 Host : {host} ({nmScan[host].hostname()})")
        print(f"📡 State : {nmScan[host].state()}")
        for proto in nmScan[host].all_protocols():
            print(f"--- Protocol: {proto} ---")
            ports = sorted(nmScan[host][proto].keys())
            for port in ports:
                state = nmScan[host][proto][port]['state']
                print(f"Port: {port}\tState: {state}")

    # Pergunta final
    continuar = input("\n🔄 Queres fazer novo scan? (s/n): ").lower()
    if continuar != 's':
        print("👋 A sair... Até à próxima!")
        break


                

DOCS 3

SETUP 3

🏠 CD ROOT /HOME..