我正在编写一个简单的程序来使用私钥/公钥验证消息。请不要担心编译,我在这里只粘贴相关的片段,编译在原始文件中没有错误。首先,我生成密钥并将它们序列化,例如:
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
_private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
public_key = private_key.public_key()
_public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
此外,我对哈希消息进行数字签名,例如:
private_key = serialization.load_pem_private_key(_private_pem, None)
message = "this is mess"
m_byte = json.dumps(message).encode('utf-8')
tm_hash = hashlib.sha256(m_byte).hexdigest()
signature = private_key.sign(
json.dumps(tm_hash).encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
signature = base64.b64encode(signature)
现在在另一个验证函数中,我编写了如下代码来验证签名:
hash_string = json.dumps(message)
encoded_hash_string = hash_string.encode('utf-8')
m_hash = hashlib.sha256(encoded_hash_string).hexdigest()
encoded_message_hash = m_hash.encode('utf-8')
signature = base64.b64decode(signature)
try:
_public_key = serialization.load_pem_public_key(_public_pem)
_public_key.verify(
signature,
encoded_message_hash,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
except InvalidSignature:
return False
return True
但这会一直返回 False,因为它遇到了异常。我已经尝试在这里打印每个变量,并且数据似乎正确。该程序基于此处给出的示例 - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa 请帮助。