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.
45 lines
1.4 KiB
45 lines
1.4 KiB
# 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()
|
|
|