DSA uses public-key cryptography. We need to first generate a DSA key pair that consists of a public key and a private key. The private key needs to be kept secret and the public key can be shared with others. We create a DSA signature using the private key and verify the signature using the public key. In other words, a sender can use her private key to create a DSA signature of a message and send the signature and the message to a recipient. The recipient can then use the public key of the sender to verify the signature.
In this article, we would generate a DSA key pair and export the public key and the private key to two files. Later, we would import the private key and create a DSA signature and import the public key to verify the signature. We would use the PyCryptodome Python module for this purpose.
We can generate DSA keys using the PyCryptodome module in the following way:
from Crypto.PublicKey import DSA keypair = DSA.generate(2048) public_key = keypair.publickey()
Please note that the keypair contains private key components. If we want to export the private key, we would need to export this keypair. The publicKey() function, on the other hand, returns the DSA public key that can be exported to a file and shared with others.
Now, we can export the private key and the public key to two files in the following way:
with open("public_key_dsa.pem", "wb") as file: file.write(public_key.exportKey('PEM')) file.close() with open("private_key_dsa.pem", "wb") as file: file.write(keypair.exportKey('PEM', True, 'MyPassphrase')) file.close()
Here, the keys are exported in ‘PEM’ format. And, we are using a passphrase to export the key so that no unauthorized party can read the private key without the secret passphrase. The second argument in the keypair.exportKey() function indicates whether the key is encoded with PKCS#8 (Public-Key Cryptography Standards #8). If pkcs8 is False, then an obsolete PEM encryption scheme is used.
Now, we would import the private key from the file private_key_dsa.pem and create a DSA signature using the private key.
from Crypto.PublicKey import DSA from Crypto.Hash import SHA256 from Crypto.Signature import DSS def create_signature(message, filename): with open(filename, "rb") as file1: private_key = DSA.importKey(file1.read(), 'MyPassphrase') message_hash = SHA256.new(message.encode()) signer = DSS.new(private_key, 'fips-186-3') signature1 = signer.sign(message_hash) return signature1
We are first generating a message hash using the SHA 256 algorithm and then signing the message …
0 Comments