You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
505/signature_2.py

45 lines
1.7 KiB

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 # 验证失败