From 2a5a8a7687629f41cf40a84f3d05d5028355c5d0 Mon Sep 17 00:00:00 2001 From: pyj256ost <2940908360@qq.com> Date: Wed, 13 Dec 2023 19:55:38 +0800 Subject: [PATCH] ADD file via upload --- digital_signature.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 digital_signature.py diff --git a/digital_signature.py b/digital_signature.py new file mode 100644 index 0000000..c50f61a --- /dev/null +++ b/digital_signature.py @@ -0,0 +1,44 @@ +# digital_signature.py + +from cryptography.hazmat.primitives.asymmetric import utils +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding +import os + +def digital_signature(file_path): + # 读取A的私钥 + with open(os.path.join(os.path.dirname(__file__), 'A_private.txt'), 'r') as file: + private_key_data = file.read() + private_key = serialization.load_pem_private_key( + private_key_data.encode(), + password=None, + backend=default_backend() + ) + + # 读取原文 + with open(file_path, 'rb') as file: + message = file.read() + + # 计算摘要 + hash_object = hashes.Hash(hashes.SHA256(), backend=default_backend()) + hash_object.update(message) + hash_value = hash_object.finalize() + + # 使用私钥进行签名 + signature = private_key.sign( + hash_value, + padding.PSS( + mgf=padding.MGF1(hashes.SHA256()), + salt_length=padding.PSS.MAX_LENGTH + ), + utils.Prehashed(hashes.SHA256()) + ) + + # 将签名保存到文件 + with open(os.path.join(os.path.dirname(__file__), 'signature.txt'), 'wb') as file: + file.write(signature) + + return hash_value.hex() +