[英]Sign a message with DSA with library pyOpenSSL
This is my first question here, because I have not found a solution for this. 这是我的第一个问题,因为我还没有找到解决方案。 Hopefully someone has an answer for this issue. 希望有人能够解决这个问题。
I try to sign and verify a message with DSA (Digital Signature Algorithm) and pyOpenSSL wrapper. 我尝试使用DSA(数字签名算法)和pyOpenSSL包装器来签名和验证消息。
I've created an example below: 我在下面创建了一个例子:
from OpenSSL.crypto import TYPE_DSA, Error, PKey
from OpenSSL.crypto import FILETYPE_PEM, sign
from Crypto.Hash import SHA
key = PKey()
key.generate_key(TYPE_DSA, 1024)
message = "abc"
digest = SHA.new(message).digest()
data_to_sign = base64.b64encode(digest)
signature = sign(key, data_to_sign, 'sha1')
After running this piece of code I'll get the following result: 运行这段代码后,我将得到以下结果:
OpenSSL.crypto.Error: [('digital envelope routines', 'EVP_SignFinal', 'wrong public key type')]
I've found the solution, but I used another python library. 我找到了解决方案,但我使用了另一个python库。 The OpenSSL library I am using on my Mac did not work for me. 我在Mac上使用的OpenSSL库对我不起作用。 I am using a 4096 bit key and the library did not supports it. 我使用4096位密钥,库不支持它。 On my linux box the following script worked. 在我的linux框中,以下脚本有效。
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import interfaces
from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
pem_data = contents = open('./pri.pem').read()
pem_public_data = contents = open('./pub.pem').read()
key = load_pem_private_key(pem_data, password=None, backend=default_backend())
if isinstance(key, interfaces.DSAPrivateKey):
msg = b"abc"
signer = key.signer(hashes.SHA1())
signer.update(msg)
signature = signer.finalize()
public_key = load_pem_public_key(pem_public_data, backend=default_backend())
verifier = public_key.verifier(signature, hashes.SHA1())
verifier.update(msg)
try:
verifier.verify()
print 'Signature is valid'
except InvalidSignature:
print 'InvalidSignature'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.