0% found this document useful (0 votes)
67 views29 pages

M.Tech - CNS LAB - AR22-2

cns

Uploaded by

24a51d5807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views29 pages

M.Tech - CNS LAB - AR22-2

cns

Uploaded by

24a51d5807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Cryptography and Network security Lab Manual

I-I M.Tech CSE

S.No ListofExperiments Page No


Write a python program to implement thefollowing
algorithms:
1 a) Ceaser Cipher
b) SubstitutionCipher
c) Hill Cipher
2 Write a python program to implement the DES
algorithm.
Write a python program to implement the Blow-
3
Fish algorithm.
Write a python program to implement the IDEA
4
algorithm.
Write a python program to implement the AES
5 algorithm.
Write a python program to implement RSA
6 algorithm.
Implement Diffie-Hellman Key Exchange algorithm
7 using python.

8 Implement the SHA-1 algorithm usingpython.

9 Implement the MD5 algorithm using python.


Write a python program to implement DSA
10 algorithm.
1. Write a python program to perform the following algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher

a) Ceaser Cipher
def caesar_cipher(text, shift, mode='encrypt'):
"""
Perform Caesar Cipher encryption or decryption.

Parameters:
text (str): The input text to encrypt or decrypt.
shift (int): The number of positions to shift the alphabet.
mode (str): 'encrypt' to encrypt, 'decrypt' to decrypt.

Returns:
str: The encrypted or decrypted text.
"""
if mode == 'decrypt':
shift = -shift

result = []
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
shifted_char = chr((ord(char) - base + shift) % 26 + base)
result.append(shifted_char)
else:
result.append(char)

return ''.join(result)

# Example usage
if __name__ == "__main__":
print("Caesar Cipher Program")
mode = input("Choose mode (encrypt/decrypt): ").strip().lower()
text = input("Enter the text: ")
shift = int(input("Enter the shift value: "))

result = caesar_cipher(text, shift, mode)


print(f"Result: {result}")

Output:

Mode: encrypt
Input Text: Hello World
Shift: 3
Result: Khoor Zruog

b) Substitution Cipher

import string
import random

def generate_key():
"""
Generates a random substitution cipher key.

Returns:
dict: A dictionary mapping each letter to its substitution.
"""
alphabet = string.ascii_lowercase
shuffled = list(alphabet)
random.shuffle(shuffled)
return dict(zip(alphabet, shuffled))

def substitution_cipher(text, key, mode='encrypt'):


"""
Perform Substitution Cipher encryption or decryption.

Parameters:
text (str): The input text to encrypt or decrypt.
key (dict): The substitution cipher key.
mode (str): 'encrypt' to encrypt, 'decrypt' to decrypt.

Returns:
str: The encrypted or decrypted text.
"""
if mode == 'decrypt':
key = {v: k for k, v in key.items()} # Reverse the key for decryption

result = []
for char in text:
if char.isalpha():
is_upper = char.isupper()
substituted_char = key[char.lower()]
result.append(substituted_char.upper() if is_upper else
substituted_char)
else:
result.append(char)

return ''.join(result)

# Example usage
if __name__ == "__main__":
print("Substitution Cipher Program")

# Replace interactive inputs with predefined values for testing and non-
interactive environments
predefined_mode = 'encrypt' # Change to 'decrypt' as needed
predefined_text = "Hello World" # Replace with the text to encrypt or decrypt

if predefined_mode == 'encrypt':
key = generate_key()
print("Generated Key:", key)
else:
# Provide a predefined key for decryption
key = {
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's',
'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k',
'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c',
'y': 'b', 'z': 'a'
}

result = substitution_cipher(predefined_text, key, predefined_mode)


print(f"Mode: {predefined_mode}")
print(f"Input Text: {predefined_text}")
print(f"Result: {result}")

Output:

Mode: encrypt
Input Text: Hello World
Result: Duyyi Jihym

c) Hill Cipher
import numpy as np

def encrypt_hill_cipher(plaintext, key_matrix):


# Remove spaces and convert plaintext to uppercase
plaintext = plaintext.replace(" ", "").upper()

# Pad plaintext if necessary to make its length a multiple of the key matrix size
n = key_matrix.shape[0]
while len(plaintext) % n != 0:
plaintext += "X" # Padding with 'X'

# Convert plaintext to numerical values (A=0, B=1, ..., Z=25)


plaintext_numbers = [ord(char) - ord('A') for char in plaintext]

# Split plaintext into chunks of size n


chunks = [plaintext_numbers[i:i + n] for i in range(0, len(plaintext_numbers), n)]

# Encrypt each chunk


ciphertext_numbers = []
for chunk in chunks:
chunk_vector = np.array(chunk).reshape(-1, 1)
encrypted_chunk = np.dot(key_matrix, chunk_vector) % 26
ciphertext_numbers.extend(encrypted_chunk.flatten())

# Convert numerical values back to letters


ciphertext = ''.join(chr(num + ord('A')) for num in ciphertext_numbers)
return ciphertext

def main():
# Key matrix for the Hill cipher (2x2 matrix example)
key_matrix = np.array([[6, 24],
[1, 13]])

plaintext = input("Enter the plaintext: ")

# Ensure the determinant of the key matrix is non-zero modulo 26 and invertible
determinant = int(round(np.linalg.det(key_matrix))) % 26
if determinant == 0 or np.gcd(determinant, 26) != 1:
print("The key matrix is not valid for the Hill Cipher.")
return
# Encrypt the plaintext
ciphertext = encrypt_hill_cipher(plaintext, key_matrix)
print(f"Ciphertext: {ciphertext}")

if __name__ == "__main__":
main()

Output:

Plaintext: HELLO
Encrypted: CDEGVC
Decrypted: HELLO
2. Write a python program to implement the DES algorithm.
(!pip install pycryptodome) install this package

from Crypto.Cipher import DES


from Crypto.Util.Padding import pad, unpad

class DESAlgorithm:
def __init__(self, key):
if len(key) != 8:
raise ValueError("Key must be 64 bits (8 bytes) long.")
self.key = key # Properly indent this line

def encrypt(self, plaintext):


# Create a DES cipher object
cipher = DES.new(self.key, DES.MODE_ECB)

# Pad the plaintext to be a multiple of the block size


padded_plaintext = pad(plaintext, DES.block_size)

# Encrypt the padded plaintext


ciphertext = cipher.encrypt(padded_plaintext)
return ciphertext

def decrypt(self, ciphertext):


# Create a DES cipher object
cipher = DES.new(self.key, DES.MODE_ECB)

# Decrypt the ciphertext


decrypted_padded_plaintext = cipher.decrypt(ciphertext)

# Unpad the decrypted plaintext


plaintext = unpad(decrypted_padded_plaintext, DES.block_size)
return plaintext

if __name__ == "__main__":
key = b'abcdefgh' # 64-bit key (8 bytes)
plaintext = b'plaintext' # Original plaintext

des = DESAlgorithm(key)

# Encrypt the plaintext


encrypted_text = des.encrypt(plaintext)
print("Encrypted:", encrypted_text.hex())

# Decrypt the ciphertext


decrypted_text = des.decrypt(encrypted_text)
print("Decrypted:", decrypted_text.decode('utf-8'))
Output:

Encrypted: 3b03c026688e671ef5eb2c5bd8b4722d
Decrypted: plaintext
3. Write a python program to implement the Blow-Fish algorithm.

from Crypto.Cipher import Blowfish


from Crypto.Util.Padding import pad, unpad

class BlowfishAlgorithm:
def __init__(self, key):
# Validate key length (between 4 and 56 bytes)
if not (4 <= len(key) <= 56):
raise ValueError("Key must be between 32 bits (4 bytes) and 448 bits (56 bytes)
long.")
self.key = key # Proper indentation here

def encrypt(self, plaintext):


# Create a Blowfish cipher object
cipher = Blowfish.new(self.key, Blowfish.MODE_ECB)

# Pad the plaintext to be a multiple of the block size


padded_plaintext = pad(plaintext, Blowfish.block_size) # Correct indentation

# Encrypt the padded plaintext


ciphertext = cipher.encrypt(padded_plaintext)
return ciphertext

def decrypt(self, ciphertext):


# Create a Blowfish cipher object
cipher = Blowfish.new(self.key, Blowfish.MODE_ECB)

# Decrypt the ciphertext


decrypted_padded_plaintext = cipher.decrypt(ciphertext) # Correct indentation

# Unpad the decrypted plaintext


plaintext = unpad(decrypted_padded_plaintext, Blowfish.block_size)
return plaintext

if __name__ == "__main__":
key = b'secret_k' # Key (between 4 and 56 bytes)
plaintext = b'plaintext' # Original plaintext

blowfish = BlowfishAlgorithm(key)

# Encrypt the plaintext


encrypted_text = blowfish.encrypt(plaintext)
print("Encrypted:", encrypted_text.hex())

# Decrypt the ciphertext


decrypted_text = blowfish.decrypt(encrypted_text)
print("Decrypted:", decrypted_text.decode('utf-8'))

Output:

Encrypted: bbbef13a1625130ad75d01f360afc9b1
Decrypted: plaintext
4. Write a python program to implement the IDEA algorithm.

class IDEA:
def __init__(self, key):
if len(key) != 16:
raise ValueError("Key must be 128 bits (16 bytes) long.")
self.key = self.generate_subkeys(key)

def generate_subkeys(self, key):


subkeys = [0] * 52
for i in range(8):
subkeys[i] = (key[2 * i] << 8) | key[2 * i + 1]

for i in range(8, 52):


subkeys[i] = (subkeys[i - 7] << 9) | (subkeys[i - 6] >> 7) & 0xFFFF

return subkeys

def encrypt(self, plaintext):


x1 = (plaintext[0] << 8) | plaintext[1]
x2 = (plaintext[2] << 8) | plaintext[3]
x3 = (plaintext[4] << 8) | plaintext[5]
x4 = (plaintext[6] << 8) | plaintext[7]

for i in range(0, 48, 6):


x1 = self.multiply(x1, self.key[i])
x2 = (x2 + self.key[i + 1]) & 0xFFFF
x3 = (x3 + self.key[i + 2]) & 0xFFFF
x4 = self.multiply(x4, self.key[i + 3])

t1 = x1 ^ x3
t2 = self.multiply(t1, self.key[i + 4])
t3 = (t2 + (x2 ^ x4)) & 0xFFFF
t4 = self.multiply(t3, self.key[i + 5])
t5 = (t2 + t4) & 0xFFFF

x1 ^= t4
x4 ^= t4
x2 ^= t5
x3 ^= t5

if i < 42:
x2, x3 = x3, x2

x1 = self.multiply(x1, self.key[48])
x2 = (x2 + self.key[49]) & 0xFFFF
x3 = (x3 + self.key[50]) & 0xFFFF
x4 = self.multiply(x4, self.key[51])

return [(x1 >> 8) & 0xFF, x1 & 0xFF,


(x2 >> 8) & 0xFF, x2 & 0xFF,
(x3 >> 8) & 0xFF, x3 & 0xFF,
(x4 >> 8) & 0xFF, x4 & 0xFF]

def decrypt(self, ciphertext):


x1 = (ciphertext[0] << 8) | ciphertext[1]
x2 = (ciphertext[2] << 8) | ciphertext[3]
x3 = (ciphertext[4] << 8) | ciphertext[5]
x4 = (ciphertext[6] << 8) | ciphertext[7]

# Generate inverse subkeys


inv_key = self.inverse_subkeys(self.key)

for i in range(0, 48, 6):


x1 = self.multiply(x1, inv_key[i])
x2 = (x2 - inv_key[i + 1]) & 0xFFFF
x3 = (x3 - inv_key[i + 2]) & 0xFFFF
x4 = self.multiply(x4, inv_key[i + 3])
t1 = x1 ^ x3
t2 = self.multiply(t1, inv_key[i + 4])
t3 = (t2 + (x2 ^ x4)) & 0xFFFF
t4 = self.multiply(t3, inv_key[i + 5])
t5 = (t2 + t4) & 0xFFFF

x1 ^= t4
x4 ^= t4
x2 ^= t5
x3 ^= t5

if i < 42:
x2, x3 = x3, x2

x1 = self.multiply(x1, inv_key[48])
x2 = (x2 - inv_key[49]) & 0xFFFF
x3 = (x3 - inv_key[50]) & 0xFFFF
x4 = self.multiply(x4, inv_key[51])

return [(x1 >> 8) & 0xFF, x1 & 0xFF,


(x2 >> 8) & 0xFF, x2 & 0xFF,
(x3 >> 8) & 0xFF, x3 & 0xFF,
(x4 >> 8) & 0xFF, x4 & 0xFF]

def multiply(self, x, y):


if x == 0:
return 0
if y == 0:
return 0
return ((x * y) % 0x10001) % 0x10000

def inverse_subkeys(self, keys):


inv_keys = [0] * 52
for i in range(48, -1, -6):
inv_keys[i] = self.mod_inverse(keys[i], 0x10001)
inv_keys[i + 1] = (0x10000 - keys[i + 1]) & 0xFFFF
inv_keys[i + 2] = (0x10000 - keys[i + 2]) & 0xFFFF
inv_keys[i + 3] = self.mod_inverse(keys[i + 3], 0x10001)
return inv_keys

def mod_inverse(self, x, mod):


if x == 0:
return 0
t0, t1 = 0, 1
a, b = mod, x
while b > 0:
q = a // b
a, b = b, a % b
t0, t1 = t1, t0 - q * t1
return t0 % mod if t0 >= 0 else (t0 + mod)

if __name__ == "__main__":
key = bytes(range(16)) # Example 128-bit key (16 bytes)
plaintext = bytes(range(8)) # Example 64-bit block (8 bytes)

idea = IDEA(key)

# Encrypt the plaintext


encrypted_text = idea.encrypt(plaintext)
print("Encrypted:", encrypted_text)

# Decrypt the ciphertext


decrypted_text = idea.decrypt(encrypted_text)
print("Decrypted:", decrypted_text)
Output:
Encrypted: [70, 14, 124, 208, 43, 121, 181, 253]
Decrypted: [112, 245, 124, 180, 25, 108, 228, 211]
5. Write a python program to implement the AES algorithm.

from Crypto.Cipher import AES


from Crypto.Util.Padding import pad, unpad
import os

class AESAlgorithm:
def __init__(self, key):
# Validate key length (must be 16, 24, or 32 bytes for AES)
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
self.key = key # Correct indentation

def encrypt(self, plaintext):


# Create a new AES cipher object
cipher = AES.new(self.key, AES.MODE_CBC)

# Pad the plaintext to be a multiple of the block size


padded_plaintext = pad(plaintext, AES.block_size) # Correct indentation

# Encrypt the padded plaintext


ciphertext = cipher.encrypt(padded_plaintext)

# Return the initialization vector (IV) along with the ciphertext


return cipher.iv + ciphertext

def decrypt(self, ciphertext):


# Extract the IV from the beginning of the ciphertext
iv = ciphertext[:AES.block_size]
actual_ciphertext = ciphertext[AES.block_size:]

# Create a new AES cipher object with the same key and IV
cipher = AES.new(self.key, AES.MODE_CBC, iv)

# Decrypt the ciphertext


decrypted_padded_plaintext = cipher.decrypt(actual_ciphertext) # Correct indentation

# Unpad the decrypted plaintext


plaintext = unpad(decrypted_padded_plaintext, AES.block_size)
return plaintext

if __name__ == "__main__":
key = os.urandom(16) # Generate a random 128-bit key
plaintext = b'plaintext' # Original plaintext

aes = AESAlgorithm(key) # Correct indentation

# Encrypt the plaintext


encrypted_text = aes.encrypt(plaintext)
print("Encrypted:", encrypted_text.hex())

# Decrypt the ciphertext


decrypted_text = aes.decrypt(encrypted_text)
print("Decrypted:", decrypted_text.decode('utf-8'))

Output:

Encrypted: 678361adbfd360be5e83946ec00593921367f0ba2360cd62813e9ec7f94eb7cf
Decrypted: plaintext
6. Write a python program to implement RSA algorithm.

from cryptography.hazmat.backends import default_backend


from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes

class RSAAlgorithm:
def __init__(self, key_size=2048):
# Generate RSA private and public keys
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=default_backend()
)
self.public_key = self.private_key.public_key()

def encrypt(self, plaintext):


# Encrypt the plaintext using the public key
ciphertext = self.public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext

def decrypt(self, ciphertext):


# Decrypt the ciphertext using the private key
plaintext = self.private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext

def export_private_key(self):
# Export the private key in PEM format
return self.private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)

def export_public_key(self):
# Export the public key in PEM format
return self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)

if __name__ == "__main__":
rsa = RSAAlgorithm()

# Sample plaintext
plaintext = b'Hello, RSA!'

# Encrypt the plaintext


encrypted_text = rsa.encrypt(plaintext)
print("Encrypted:", encrypted_text.hex())

# Decrypt the ciphertext


decrypted_text = rsa.decrypt(encrypted_text)
print("Decrypted:", decrypted_text.decode('utf-8'))
Output:

Encrypted:
4f63fd0a9675d8a3f4ed7f6f2c1e20ebca776f1635c67e04f2430948b3bf3ecc5bb4804780955
19d7c0e8e3563e803229ccb9e7858c2fab1edf89481288f507614f9bbf86b0d86341d7014bbd
09af187bf85ff1b7ea5b82d00175bf5b7a4bb5ec3cd9be774cb0768a5356081765ce0796e721
a1c8889bba3f012f587fc7b718ae870ceb35612df2227f1fbd918068bbc11240c274f4a5acfe8
37660a91343061bf274200279817884427ac46a076d4daf19a9151d4256a1f49410f0eeea83
c6b9d72606ae3bdb6873cea0b2d292c7a3b2cf39b51cff5e905de17e6d7995c570b70abc690
1b9194860d9116570cb9032c9a7bb594e366c952c8f07c9c702361b6
Decrypted: Hello, RSA!
7. Implement the Diffie-Hellman Key Exchange mechanism using python.

import random
from hashlib import sha256

class DiffieHellman:
def __init__(self):
# Public parameters (prime number and primitive root)
self.p = 23 # A small prime number (for demonstration)
self.g = 5 # A primitive root modulo p

def generate_private_key(self):
# Generate a private key
return random.randint(1, self.p - 1)

def generate_public_key(self, private_key):


# Calculate public key using the formula: g^private_key mod p
return pow(self.g, private_key, self.p)

def compute_shared_secret(self, public_key, private_key):


# Calculate the shared secret using the formula: public_key^private_key mod
p
return pow(public_key, private_key, self.p)

if __name__ == "__main__":
# Alice's side
alice = DiffieHellman()
alice_private_key = alice.generate_private_key()
alice_public_key = alice.generate_public_key(alice_private_key)

print(f"Alice's Private Key: {alice_private_key}")


print(f"Alice's Public Key: {alice_public_key}")

# Bob's side
bob = DiffieHellman()
bob_private_key = bob.generate_private_key()
bob_public_key = bob.generate_public_key(bob_private_key)

print(f"Bob's Private Key: {bob_private_key}")


print(f"Bob's Public Key: {bob_public_key}")

# Exchange public keys and compute shared secret


alice_shared_secret = alice.compute_shared_secret(bob_public_key,
alice_private_key)
bob_shared_secret = bob.compute_shared_secret(alice_public_key,
bob_private_key)

print(f"Alice's Shared Secret: {alice_shared_secret}")


print(f"Bob's Shared Secret: {bob_shared_secret}")

# Verify that both shared secrets are equal


assert alice_shared_secret == bob_shared_secret, "Shared secrets do not
match!"
print("Shared secrets match!")

Output:
Alice's Private Key: 12
Alice's Public Key: 18
Bob's Private Key: 22
Bob's Public Key: 1
Alice's Shared Secret: 1
Bob's Shared Secret: 1
Shared secrets match!
8. Implement the SHA-1 algorithm using python.

import hashlib

class SHA1:
def __init__(self):
# Initialize SHA-1 hash object
self.sha1_hash = hashlib.sha1()

def update(self, data):


"""Update the hash object with the bytes-like object."""
self.sha1_hash.update(data)

def digest(self):
"""Return the hexadecimal digest of the hash."""
return self.sha1_hash.hexdigest()

def compute_hash(self, text):


"""Compute SHA-1 hash for the given text."""
self.update(text.encode('utf-8')) # Convert text to bytes
return self.digest()

if __name__ == "__main__":
# Example input text
text = "Hello, SHA-1!"

# Create a SHA1 object


sha1 = SHA1()

# Compute the SHA-1 hash


hash_value = sha1.compute_hash(text)

# Display the result


print(f"Text: {text}")
print(f"SHA-1 Hash: {hash_value}")

Output:

Text: Hello, SHA-1!


SHA-1 Hash: f322e078fef4f49da1618d3793d3272a91f0488c
9. Implement the MD5 algorithm using python.

import hashlib

class MD5:
def __init__(self):
# Initialize MD5 hash object
self.md5_hash = hashlib.md5()

def update(self, data):


"""Update the hash object with the bytes-like object."""
self.md5_hash.update(data)

def digest(self):
"""Return the hexadecimal digest of the hash."""
return self.md5_hash.hexdigest()

def compute_hash(self, text):


"""Compute MD5 hash for the given text."""
self.update(text.encode('utf-8')) # Convert text to bytes
return self.digest() # Correct indentation here

if __name__ == "__main__":
# Example input text
text = "Hello, MD5!"

# Create an MD5 object


md5 = MD5()

# Compute the MD5 hash


hash_value = md5.compute_hash(text)

# Display the result


print(f"Text: {text}")
print(f"MD5 Hash: {hash_value}")

Output:
Text: Hello, MD5!
MD5 Hash: 65a5056b6e8b4a877305f6f42790f7ec

10. Write a python program to implement DSA algorithm.


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
from cryptography.hazmat.primitives import hashes

class DSAAlgorithm:
def __init__(self):
# Generate a private key for use in the DSA algorithm
self.private_key = dsa.generate_private_key(key_size=2048,
backend=default_backend())
self.public_key = self.private_key.public_key()

def sign_message(self, message):


"""Sign a message using the private key."""
# Hash the message
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(message.encode('utf-8'))
digest_final = digest.finalize()

# Sign the hashed message


signature = self.private_key.sign(
digest_final,
Prehashed(hashes.SHA256())
)
return signature

def verify_signature(self, message, signature):


"""Verify a signature using the public key."""
# Hash the message
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(message.encode('utf-8'))
digest_final = digest.finalize()

# Verify the signature


try:
self.public_key.verify(
signature,
digest_final,
Prehashed(hashes.SHA256())
)
return True
except Exception as e:
print(f"Verification failed: {e}")
return False

if __name__ == "__main__":
# Create an instance of DSAAlgorithm
dsa_instance = DSAAlgorithm()

# Example message
message = "Hello, DSA!"

# Sign the message


signature = dsa_instance.sign_message(message)
print("Signature:", signature.hex())

# Verify the signature


is_verified = dsa_instance.verify_signature(message, signature)
print("Verification:", "Successful" if is_verified else "Failed")

Output:

Signature:
30440220409b2a7bd6987f5a0a9ad8d50ce1ced16e964ed166d6b6c039904657929
f5e7a02207a5498d9609c7c8a2af5a1f2a5a15e25a1234b14231a0b5d76c1b919f85
0ef09
Verification: Successful

You might also like