tuhbooh's picture
Update app.py
6ba5005 verified
import os
import gradio as gr
import numpy as np
import hashlib
from fpdf import FPDF
from datetime import datetime
# --- 1. SETUP THUẬT TOÁN (Giữ nguyên) ---
SECRET_CODE = os.getenv("ES")
exec_context = {}
encrypt_fn = decrypt_fn = None
if SECRET_CODE:
try:
exec(SECRET_CODE, exec_context)
encrypt_fn, decrypt_fn = exec_context.get('transform_byte'), exec_context.get('untransform_byte')
except Exception as e: print(f"Error: {e}")
def get_file_sha256(file_path):
h = hashlib.sha256()
with open(file_path, 'rb') as f:
while chunk := f.read(8192): h.update(chunk)
return h.hexdigest()
# --- 2. HÀM THIẾT KẾ CHỨNG CHỈ SIÊU CẤP ---
class T4S_PDF(FPDF):
def header(self):
# Vẽ một thanh header màu xanh đậm
self.set_fill_color(44, 62, 80)
self.rect(0, 0, 297, 30, 'F')
self.set_text_color(255, 255, 255)
self.set_font("Helvetica", "B", 20)
self.cell(0, 10, "TITANIUM4S - QUANTUM SECURE PROTOCOL", ln=True, align="C")
self.set_font("Helvetica", "", 10)
self.cell(0, 5, "Official Security Audit & Ownership Certificate", ln=True, align="C")
def footer(self):
self.set_y(-20)
self.set_font("Helvetica", "I", 8)
self.set_text_color(150, 150, 150)
self.cell(0, 10, f"Issued by Titanium4S Zero-Trust Engine | Record ID: {hashlib.md5(str(datetime.now()).encode()).hexdigest()[:10].upper()}", align="C")
def create_detailed_pdf(file_name, sha_hash, password, output_path):
pdf = T4S_PDF(orientation="L", unit="mm", format="A4")
pdf.add_page()
# 1. PHẦN THÔNG TIN FILE (Bố cục cột)
pdf.ln(10)
pdf.set_text_color(0, 0, 0)
pdf.set_font("Helvetica", "B", 16)
pdf.cell(0, 10, "1. PROTECTED ASSET IDENTITY", ln=True)
pdf.set_line_width(0.5); pdf.set_draw_color(44, 62, 80); pdf.line(10, pdf.get_y(), 287, pdf.get_y())
pdf.ln(5)
pdf.set_font("Helvetica", "", 12)
pdf.cell(40, 10, "Filename:", 0); pdf.set_font("Helvetica", "B", 12); pdf.cell(0, 10, file_name, ln=True)
pdf.set_font("Helvetica", "", 12)
pdf.cell(40, 10, "SHA-256 Fingerprint:", 0); pdf.set_font("Courier", "B", 10); pdf.cell(0, 10, sha_hash, ln=True)
# 2. PHẦN CÔNG NGHỆ (Technology Overview)
pdf.ln(10)
pdf.set_font("Helvetica", "B", 16)
pdf.cell(0, 10, "2. TECHNOLOGY SPECIFICATION", ln=True)
pdf.set_line_width(0.5); pdf.line(10, pdf.get_y(), 287, pdf.get_y())
pdf.ln(5)
pdf.set_font("Helvetica", "", 11)
tech_info = (
"- Key Stretching: SHA-512 (10,000 Iterations) - Immunity against ASIC/GPU brute-force.\n"
"- Cipher Core: Vectorized Non-linear Transformation (Proprietary ES Logic).\n"
"- Protocol: Zero-Knowledge Proof (The system never stores your secret key)."
)
pdf.multi_cell(0, 7, tech_info)
# 3. PHẦN MẬT KHẨU & CẢNH BÁO (Làm nổi bật)
pdf.ln(10)
pdf.set_fill_color(254, 249, 231) # Màu vàng nhạt cho vùng password
pdf.rect(10, pdf.get_y(), 277, 25, 'F')
pdf.set_y(pdf.get_y() + 5)
pdf.set_font("Helvetica", "B", 14); pdf.set_text_color(192, 57, 43)
pdf.cell(0, 5, "CRITICAL: YOUR SECRET KEY RECORD", ln=True, align="C")
pdf.set_font("Courier", "B", 18)
pdf.cell(0, 12, password, ln=True, align="C")
# 4. LỜI NHẮC CỦA TITANIUM4S
pdf.ln(15)
pdf.set_text_color(44, 62, 80)
pdf.set_font("Helvetica", "B", 12)
pdf.cell(0, 10, "SECURITY COMPLIANCE & WARNINGS:", ln=True)
pdf.set_font("Helvetica", "", 10)
pdf.multi_cell(0, 6, (
"1. This PDF is the only proof of ownership. If deleted, there is no backup on any server.\n"
"2. The file .impossible is mathematically locked. Brute-forcing would take centuries with current hardware.\n"
"3. Please store this certificate in a secure vault or an offline encrypted drive."
))
# Đóng dấu "TOP SECRET" giả lập
pdf.set_font("Helvetica", "B", 50)
pdf.set_text_color(231, 76, 60)
pdf.rotate(25, 200, 150)
pdf.text(180, 180, "TOP SECRET")
pdf.rotate(0)
pdf.output(output_path)
return output_path
# --- 3. LOGIC XỬ LÝ CHÍNH ---
def stretch_key(password):
key = password.encode() + b"MinhDuc_Zero_Trust_Protocol"
for _ in range(10000): key = hashlib.sha512(key).digest()
return key[:32]
def process_file(file, password, mode, progress=gr.Progress()):
if not encrypt_fn: return None, "❌ Secret ES Error!"
master_key = np.frombuffer(stretch_key(password), dtype=np.uint8)
input_path = file.name
original_name = os.path.basename(input_path)
is_encrypt = (mode == "Mã hóa")
output_name = original_name + ".impossible" if is_encrypt else (original_name.replace(".impossible", "") if original_name.endswith(".impossible") else "rebuilt_" + original_name)
output_path = os.path.join(os.path.dirname(input_path), output_name)
file_size = os.path.getsize(input_path)
chunk_size = 4 * 1024 * 1024
bytes_processed = 0
fn = encrypt_fn if is_encrypt else decrypt_fn
try:
file_hash = get_file_sha256(input_path) if is_encrypt else "N/A"
with open(input_path, 'rb') as f_in, open(output_path, 'wb') as f_out:
while True:
chunk = f_in.read(chunk_size)
if not chunk: break
data_arr = np.frombuffer(chunk, dtype=np.uint8)
indices = np.arange(bytes_processed, bytes_processed + len(data_arr), dtype=np.uint64)
key_chunk = master_key[indices % 32]
f_out.write(fn(data_arr, key_chunk, indices).astype(np.uint8).tobytes())
bytes_processed += len(chunk)
progress(bytes_processed / file_size, desc=f"Processing {mode}...")
if is_encrypt:
pdf_path = os.path.join(os.path.dirname(input_path), f"Audit_{original_name}.pdf")
create_detailed_pdf(original_name, file_hash, password, pdf_path)
return [output_path, pdf_path], "✅ Đã mã hóa & Xuất hồ sơ bảo mật!"
return [output_path], "✅ Giải mã thành công!"
except Exception as e: return None, f"❌ Lỗi: {str(e)}"
# --- 4. GIAO DIỆN ---
with gr.Blocks(theme=gr.themes.Monochrome(), title="Titanium4S Vault") as demo:
gr.Markdown("# 🛡️ Titanium4S - Ultimate Audit Edition")
with gr.Row():
with gr.Column():
inp_file = gr.File(label="Target File")
inp_pass = gr.Textbox(label="Secret Key", type="password")
inp_mode = gr.Radio(["Mã hóa", "Giải mã"], label="Mode", value="Mã hóa")
btn = gr.Button("INITIALIZE PROTOCOL", variant="primary")
with gr.Column():
out_files = gr.File(label="Output Assets", file_count="multiple")
status = gr.Textbox(label="System Status", interactive=False)
btn.click(process_file, [inp_file, inp_pass, inp_mode], [out_files, status])
demo.queue(1).launch(ssr_mode=False)