如何在Python中生成字符串的数字签名?

问题描述 投票:0回答:2

我有一个字符串,我需要使用我的私钥为其生成数字签名?我怎样才能用Python做到这一点?

python digital-signature
2个回答
12
投票

您可以使用 Cryptography 模块生成私钥,然后使用 RSA 签署您的字符串

# Generate a private key   
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )

# Sign a message using the key
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import padding
>>> message = b"A message I want to sign"
>>> signature = private_key.sign(
...     message,
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )

如果您已经拥有想要使用的私钥,那么您可以加载它,而不是生成新的私钥。


0
投票

来自 chat-gpt

import hashlib

def generate_unique_signature(input_string):
    # Create a SHA-256 hash object
    sha256 = hashlib.sha256()

    # Update the hash object with the input string
    sha256.update(input_string.encode('utf-8'))

    # Get the hexadecimal representation of the hash
    signature = sha256.hexdigest()

    return signature

# Example usage:
input_string = "Hello, World!"
signature = generate_unique_signature(input_string)
print("Unique Signature:", signature)
© www.soinside.com 2019 - 2024. All rights reserved.