数字签名 #2

Merged
psyfbu5z8 merged 3 commits from sheep into main 1 year ago

@ -0,0 +1,54 @@
## Python file to initialize the overall progress of the file transmit
## Finished May 31 2:20 p.m.
import os
import shutil
def does_not_exist(directory_path):
if os.path.exists(directory_path):
return False
return True
def not_empty_dir(directory_path):
if len(os.listdir(directory_path)) == 0:
return False
return True
if does_not_exist('inbox'):
os.mkdir('inbox')
if does_not_exist('outbox'):
os.mkdir('outbox')
if does_not_exist('sent'):
os.mkdir('sent')
if does_not_exist('sandbox_receiver'):
os.mkdir('sandbox_receiver')
if not_empty_dir('inbox'):
shutil.rmtree(r'inbox')
os.mkdir(r'inbox')
if not_empty_dir('sent'):
shutil.rmtree(r'sent')
os.mkdir(r'sent')
if not_empty_dir('outbox'):
shutil.rmtree(r'outbox')
os.mkdir(r'outbox')
try:
os.unlink('public_key_sender.txt')
os.unlink('public_key_sender.pem')
os.unlink('public_key_receiver.txt')
os.unlink('sandbox_sender/private_key_sender.txt')
os.unlink('sandbox_sender/private_key_sender.pem')
os.unlink('sandbox_receiver/private_key_receiver.txt')
except Exception as ex:
print("文件已被初始化")
print('Initialization Complete')

@ -0,0 +1,50 @@
import hashlib
from Crypto.PublicKey import RSA
from Crypto.Cipher import DES
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from Crypto.Cipher import PKCS1_OAEP
def sign():
# 读取文件中的消息内容
with open('sandbox_sender/sample.txt', 'rb') as original_file:
message = original_file.read() # 以二进制方式读取消息
# 读取私钥文件并加载私钥
with open('sandbox_sender/private_key_sender.pem', 'rb') as private_key_file:
private_key = serialization.load_pem_private_key(
private_key_file.read(),
password=None,
backend=default_backend()
)
# 创建消息的哈希
message_hash = hashes.Hash(hashes.SHA256(), backend=default_backend())
message_hash.update(message) # 使用文件内容更新哈希
digest = message_hash.finalize()
# 使用 PSS 填充对消息进行签名
signature = private_key.sign(
digest,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
# 将签名转换为十六进制字符串
signature_hex = signature.hex()
# 打印签名
#print(f"Signature (Hex): {signature_hex}")
# 保存签名为十六进制字符串到文件
with open('outbox/signature.txt', 'w') as f:
f.write(signature_hex)
print("Signature saved as hex in 'outbox/signature.txt'.")
return signature

@ -0,0 +1,45 @@
from Crypto.Cipher import DES
import binascii
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
def verify():
# 读取解密后的消息内容
with open('inbox/decrypted_msg.txt', 'rb') as decrypted_file:
message = decrypted_file.read() # 以二进制方式读取消息
# 从 PEM 文件中加载公钥
with open('public_key_sender.pem', 'rb') as f: # 以二进制模式打开
public_key = serialization.load_pem_public_key(f.read(), backend=default_backend())
# 读取十六进制格式的签名
with open('sent/signature.txt', 'r') as signature_file:
hex_signature = signature_file.read().strip() # 读取并去掉两端的空白字符
# 将十六进制签名转换为字节数据
signature = bytes.fromhex(hex_signature)
# 计算消息的哈希(应与签名时一致)
message_hash = hashes.Hash(hashes.SHA256(), backend=default_backend())
message_hash.update(message)
digest = message_hash.finalize()
try:
# 使用公钥对签名进行验证
public_key.verify(
signature,
digest, # 使用哈希值进行验证
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
print("Signature verified successfully.")
return True # 验证成功
except Exception as e:
print(f"Verification failed: {e}")
return False # 验证失败
Loading…
Cancel
Save