我有一个字符串,我需要使用我的私钥为其生成数字签名?我怎样才能用Python做到这一点?
您可以使用 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()
... )
如果您已经拥有想要使用的私钥,那么您可以加载它,而不是生成新的私钥。
来自 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)