ADD file via upload

main
pyj256ost 12 months ago
parent 9b7716df46
commit 2a5a8a7687

@ -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()
Loading…
Cancel
Save