初次提交
This commit is contained in:
226
backend/simple_hash_demo.py
Normal file
226
backend/simple_hash_demo.py
Normal file
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
简化版文件哈希演示脚本
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import requests
|
||||
import os
|
||||
|
||||
# API基础URL
|
||||
BASE_URL = "http://localhost:8000/api/v1"
|
||||
USER_ID = 8
|
||||
|
||||
def calculate_sha256_hash(file_content: bytes) -> str:
|
||||
"""计算文件的SHA-256哈希值"""
|
||||
return hashlib.sha256(file_content).hexdigest()
|
||||
|
||||
def upload_and_demo_hash():
|
||||
"""上传文件并演示哈希功能"""
|
||||
|
||||
# 创建测试文件内容
|
||||
original_content = "Hello World! 这是演示文件哈希的测试内容。"
|
||||
|
||||
print("=== 文件哈希演示 ===")
|
||||
print("原始文件内容:")
|
||||
print(f"'{original_content}'")
|
||||
print(f"文件大小: {len(original_content.encode('utf-8'))} bytes")
|
||||
print()
|
||||
|
||||
# 计算哈希值
|
||||
file_hash = calculate_sha256_hash(original_content.encode('utf-8'))
|
||||
print("计算的SHA-256哈希值:")
|
||||
print(file_hash)
|
||||
print()
|
||||
|
||||
# 上传文件
|
||||
try:
|
||||
files = {
|
||||
"file": ("hash_demo.txt", original_content.encode('utf-8'), "text/plain")
|
||||
}
|
||||
data = {
|
||||
"user_id": USER_ID,
|
||||
"description": "哈希演示文件",
|
||||
"tags": "demo,hash",
|
||||
"is_public": "false"
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
f"{BASE_URL}/files/upload",
|
||||
files=files,
|
||||
data=data
|
||||
)
|
||||
|
||||
if response.status_code == 201:
|
||||
result = response.json()
|
||||
if result.get("success"):
|
||||
file_info = result["data"]["file"]
|
||||
server_hash = file_info["file_hash"]
|
||||
file_id = file_info["id"]
|
||||
|
||||
print("文件上传成功!")
|
||||
print(f"文件ID: {file_id}")
|
||||
print(f"服务器哈希值: {server_hash}")
|
||||
print()
|
||||
|
||||
# 验证哈希值一致性
|
||||
if file_hash == server_hash:
|
||||
print("哈希值验证通过! 客户端和服务器计算结果一致")
|
||||
else:
|
||||
print("哈希值验证失败!")
|
||||
print(f"客户端: {file_hash}")
|
||||
print(f"服务器: {server_hash}")
|
||||
|
||||
return file_id, original_content, file_hash, file_info['filename']
|
||||
else:
|
||||
print(f"上传失败: {response.text}")
|
||||
return None, None, None, None
|
||||
|
||||
except Exception as e:
|
||||
print(f"上传出错: {e}")
|
||||
return None, None, None, None
|
||||
|
||||
def verify_download_integrity(file_id, original_content, original_hash, filename):
|
||||
"""验证下载文件的完整性"""
|
||||
|
||||
print("\n=== 文件下载和完整性验证 ===")
|
||||
|
||||
try:
|
||||
# 下载文件
|
||||
data = {
|
||||
"user_id": USER_ID,
|
||||
"file_id": file_id
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
f"{BASE_URL}/files/download",
|
||||
json=data
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
downloaded_content = response.content.decode('utf-8')
|
||||
|
||||
print("下载的文件内容:")
|
||||
print(f"'{downloaded_content}'")
|
||||
print()
|
||||
|
||||
# 验证内容完整性
|
||||
if downloaded_content == original_content:
|
||||
print("内容完整性验证通过!")
|
||||
else:
|
||||
print("内容完整性验证失败!")
|
||||
|
||||
# 计算下载文件的哈希值
|
||||
downloaded_hash = calculate_sha256_hash(downloaded_content.encode('utf-8'))
|
||||
print("下载文件的哈希值:")
|
||||
print(downloaded_hash)
|
||||
print()
|
||||
|
||||
# 验证哈希值
|
||||
if downloaded_hash == original_hash:
|
||||
print("下载文件哈希验证通过! 文件完整性得到保证")
|
||||
else:
|
||||
print("下载文件哈希验证失败! 文件可能已损坏")
|
||||
print(f"原始哈希: {original_hash}")
|
||||
print(f"下载哈希: {downloaded_hash}")
|
||||
|
||||
else:
|
||||
print(f"下载失败: {response.text}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"下载过程出错: {e}")
|
||||
|
||||
def show_server_file_info(filename):
|
||||
"""显示服务器上文件的信息"""
|
||||
|
||||
print("\n=== 服务器文件信息 ===")
|
||||
|
||||
# 检查uploads目录
|
||||
upload_path = os.path.join("uploads", filename)
|
||||
if os.path.exists(upload_path):
|
||||
file_size = os.path.getsize(upload_path)
|
||||
print(f"文件路径: {upload_path}")
|
||||
print(f"文件大小: {file_size} bytes")
|
||||
|
||||
# 计算文件哈希
|
||||
with open(upload_path, 'rb') as f:
|
||||
content = f.read()
|
||||
file_hash = calculate_sha256_hash(content)
|
||||
print(f"文件SHA-256哈希: {file_hash}")
|
||||
|
||||
# 显示文件内容
|
||||
with open(upload_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
print(f"文件内容: '{content}'")
|
||||
else:
|
||||
print(f"文件不存在: {upload_path}")
|
||||
|
||||
def demonstrate_hash_properties():
|
||||
"""演示哈希的重要特性"""
|
||||
|
||||
print("\n=== 哈希特性演示 ===")
|
||||
|
||||
# 特性1: 相同输入产生相同哈希
|
||||
text1 = "Hello World"
|
||||
text2 = "Hello World"
|
||||
hash1 = calculate_sha256_hash(text1.encode())
|
||||
hash2 = calculate_sha256_hash(text2.encode())
|
||||
|
||||
print("特性1: 相同输入产生相同哈希")
|
||||
print(f"文本1: '{text1}' -> {hash1}")
|
||||
print(f"文本2: '{text2}' -> {hash2}")
|
||||
print(f"哈希值相同: {hash1 == hash2}")
|
||||
print()
|
||||
|
||||
# 特性2: 微小变化导致完全不同的哈希
|
||||
text3 = "Hello World"
|
||||
text4 = "Hello World!" # 只多了一个感叹号
|
||||
hash3 = calculate_sha256_hash(text3.encode())
|
||||
hash4 = calculate_sha256_hash(text4.encode())
|
||||
|
||||
print("特性2: 微小变化导致完全不同的哈希")
|
||||
print(f"文本3: '{text3}' -> {hash3}")
|
||||
print(f"文本4: '{text4}' -> {hash4}")
|
||||
print(f"哈希值不同: {hash3 != hash4}")
|
||||
print()
|
||||
|
||||
# 特性3: 不可逆性
|
||||
sample_hash = "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"
|
||||
print("特性3: 哈希是单向的,无法从哈希反推原始内容")
|
||||
print(f"示例哈希: {sample_hash}")
|
||||
print("无法从这个哈希值推断出原始文本内容")
|
||||
print()
|
||||
|
||||
def main():
|
||||
"""主演示函数"""
|
||||
|
||||
# 演示哈希特性
|
||||
demonstrate_hash_properties()
|
||||
|
||||
# 上传并演示哈希功能
|
||||
file_id, original_content, original_hash, filename = upload_and_demo_hash()
|
||||
|
||||
if file_id:
|
||||
# 验证下载完整性
|
||||
verify_download_integrity(file_id, original_content, original_hash, filename)
|
||||
|
||||
# 显示服务器文件信息
|
||||
show_server_file_info(filename)
|
||||
|
||||
print("\n=== 总结 ===")
|
||||
print("file_hash 的作用:")
|
||||
print("1. 完整性验证 - 确保文件在传输存储过程中未损坏")
|
||||
print("2. 文件去重 - 相同内容只存储一份,节省空间")
|
||||
print("3. 安全检查 - 防止恶意文件和内容篡改")
|
||||
print("4. 快速比较 - 通过哈希值快速判断文件是否相同")
|
||||
print()
|
||||
print("如何还原文件:")
|
||||
print("1. 通过API下载: POST /api/v1/files/download")
|
||||
print("2. 直接从服务器目录读取: backend/uploads/[filename]")
|
||||
print("3. 验证文件完整性: 计算SHA-256哈希并与数据库中的file_hash比较")
|
||||
|
||||
else:
|
||||
print("演示失败,无法上传测试文件")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user