简体   繁体   中英

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.

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. The OpenSSL library I am using on my Mac did not work for me. I am using a 4096 bit key and the library did not supports it. On my linux box the following script worked.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM