Program – 01
Write a Python Program to Implement Basic RSA Encryption and
Decryption
p = 17
q = 23
n=p*q
phi = (p - 1) * (q - 1)
e=7
for d in range(1, phi):
if (d * e) % phi == 1:
break
public_key = (e, n)
private_key = (d, n)
def encrypt(msg, key):
e, n = key
return [(ord(char) ** e) % n for char in msg]
def decrypt(cipher, key):
d, n = key
return ''.join([chr((char ** d) % n) for char in cipher])
message = "HI"
encrypted = encrypt(message, public_key)
decrypted = decrypt(encrypted, private_key)
print("Original message:", message)
print("Encrypted:", encrypted)
print("Decrypted:", decrypted)
1
Output:
2
Program – 02
Write a Python Program to Implement the Diffie–Hellman Key Exchange
Algorithm
p = 23
g=5
a=6
A = (g ** a) % p
b = 15
B = (g ** b) % p
shared_secret_alice = (B ** a) % p
shared_secret_bob = (A ** b) % p
print("Public parameters: p =", p, ", g =", g)
print("Alice's private key:", a)
print("Alice's public key: ", A)
print("Bob's private key: ", b)
print("Bob's public key: ", B)
print("Shared secret (Alice):", shared_secret_alice)
print("Shared secret (Bob): ", shared_secret_bob)
3
Output:
4
Program – 03
Write a Python Program to Generate a SHA-256 Hash Using the hashlib
Library
import hashlib
data = "Hey".encode()
sha256_hash = hashlib.sha256()
sha256_hash.update(data
hash_hex = sha256_hash.hexdigest()
print("SHA-256 hash:", hash_hex)
Output:
5
Program – 04
Write a Python Program to Create a Simple Block Class and Generate a
Blockchain Block with SHA-256 Hashing
class Block:
def __init__(self, data):
[Link] = data
def show_data(self):
print("Data inside block:", [Link])
block1 = Block("Hello")
block1.show_data()
import hashlib
import time
class Block:
def __init__(self, index, data, previous_hash):
[Link] = index
[Link] = [Link]("%Y-%m-%d %H:%M:%S")
[Link] = data
self.previous_hash = previous_hash
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = f"{[Link]}{[Link]}{[Link]}{self.previous_hash}"
return hashlib.sha256(block_string.encode()).hexdigest()
block = Block(1, "My jelesis block", "0")
print("Block index:", [Link])
print("Block Hash:", [Link])
print("Block Data:", [Link])
print("Block previous_hash:", block.previous_hash)
print("Block timestamp:", [Link])
6
Output:
7
Program – 05
Write a Python Program to Implement a Basic Blockchain With Genesis
Block, Hashing, and Block Addition
import hashlib
import time
class Block:
def __init__(self, index, data, previous_hash):
[Link] = index
[Link] = [Link]()
[Link] = data
self.previous_hash = previous_hash
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = f"{[Link]}{[Link]}{[Link]}{self.previous_hash}"
return hashlib.sha256(block_string.encode()).hexdigest()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "Genesis Block", "0")
def get_latest_block(self):
return [Link][-1]
def add_block(self, data):
latest_block = self.get_latest_block()
new_index = latest_block.index + 1
new_block = Block(new_index, data, latest_block.hash)
[Link](new_block)
my_blockchain = Blockchain()
my_blockchain.add_block("My first block")
8
my_blockchain.add_block("My second block")
my_blockchain.add_block("My third block")
for block in my_blockchain.chain:
print(f"Index: {[Link]}")
print(f"Timestamp: {[Link]([Link])}")
print(f"Data: {[Link]}")
print(f"Previous Hash: {block.previous_hash}")
print(f"Hash: {[Link]}")
Output:
9
Program – 06
Write a Solidity Program to Create an ERC-20 Token Using OpenZeppelin
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/[Link]";
contract MyToken is ERC20 {
address public owner;
constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
owner = [Link];
_mint([Link], initialSupply);
function mint(address to, uint256 amount) public {
require([Link] == owner, "Only owner can mint");
_mint(to, amount);
}
function burn(uint256 amount) public {
_burn([Link], amount);
10
Output:
11
Program – 07
Write a Python Program to Hash a Blockchain Block Using SHA-256
import hashlib
import json
import time
def hash_block(block_data):
block_string = [Link](block_data, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
if __name__ == "__main__":
new_block = {
"index": 1,
"timestamp": [Link](),
"data": {
"sender": "Anu",
"receiver": "Babo",
"amount": 50
},
"previous_hash": "0000ab34cd56ef..."
block_hash = hash_block(new_block)
print("Block data:", new_block)
print("\nBlock Hash:", block_hash)
12
Output:
13
Program – 08
Write a Python Program to Implement a Simple Blockchain with Hashing
and Validation
import hashlib
import time
import json
class Block:
def __init__(self, index, previous_hash, data, timestamp=None):
[Link] = index
self.previous_hash = previous_hash
[Link] = timestamp or [Link]()
[Link] = data
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = [Link]({
"index": [Link],
"previous_hash": self.previous_hash,
"timestamp": [Link],
"data": [Link]
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "0", "Genesis Block")
def get_latest_block(self):
return [Link][-1]
14
def add_block(self, data):
latest_block = self.get_latest_block()
new_block = Block(
index=latest_block.index + 1,
previous_hash=latest_block.hash,
data=data )
[Link](new_block)
def is_valid(self):
for i in range(1, len([Link])):
current = [Link][i]
previous = [Link][i - 1]
if [Link] != current.calculate_hash():
if current.previous_hash != [Link]:
return False
return True
if __name__ == "__main__":
blockchain = Blockchain()
blockchain.add_block("First block data")
blockchain.add_block("Second block data")
for block in [Link]:
print(f"Index: {[Link]}")
print(f"Data: {[Link]}")
print(f"Hash: {[Link]}")
print(f"Previous Hash: {block.previous_hash}")
print("-" * 40)
print("Blockchain valid:", blockchain.is_valid())
15
Output:
16
Program – 09
Write a Python Program to Implement Blockchain Transactions and
Mining Using SHA-256
import hashlib
import json
import time
class Block:
def __init__(self, index, previous_hash, transactions, timestamp=None):
[Link] = index
self.previous_hash = previous_hash
[Link] = timestamp or [Link]()
[Link] = transactions
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = [Link]({
"index": [Link],
"previous_hash": self.previous_hash,
"timestamp": [Link],
"transactions": [Link]
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
self.transaction_pool = []
def create_genesis_block(self):
return Block(0, "0", ["Genesis Block"])
def get_latest_block(self):
return [Link][-1]
17
def add_transaction(self, sender, receiver, amount):
tx = {
"sender": sender,
"receiver": receiver,
"amount": amount
self.transaction_pool.append(tx)
def mine_block(self):
if not self.transaction_pool:
print("No transactions to add.")
return
latest_block = self.get_latest_block()
new_block = Block(
index=latest_block.index + 1,
previous_hash=latest_block.hash,
transactions=self.transaction_pool
[Link](new_block)
self.transaction_pool = []
print("Block mined with transactions!")
def print_chain(self):
for block in [Link]:
print("\n--- BLOCK", [Link], "---")
print("Prev Hash:", block.previous_hash)
print("Hash:", [Link])
print("Transactions:", [Link])
if __name__ == "__main__":
18
bc = Blockchain()
bc.add_transaction("Nisha", "chaitanya", 50)
bc.add_transaction("Charlie", "Dhrub", 20)
bc.mine_block()
bc.add_transaction("Juhi", "Kartik", 100)
bc.mine_block()
bc.print_chain()
19
Output:
20
Program – 10
Write a Python Program to Implement a Proof-of-Work Algorithm Using
SHA-256
import hashlib
import time
def proof_of_work(data, difficulty):
nonce = 0
prefix = '0' * difficulty
start_time = [Link]()
while True:
text = f"{data}{nonce}"
hash_result = hashlib.sha256([Link]()).hexdigest()
if hash_result.startswith(prefix):
end_time = [Link]()
print("Block mined!")
print(f"Nonce: {nonce}")
print(f"Hash: {hash_result}")
print(f"Time taken: {end_time - start_time:.2f} seconds")
return nonce, hash_result
nonce += 1
data = "Hello, Proof of Work!"
difficulty = 4
proof_of_work(data, difficulty)
21
Output:
22
Program – 11
Write a Python Program to Register Blockchain Network Nodes and
Display Them
import hashlib
import json
import time
from [Link] import urlparse
class Block:
def __init__(self, index, previous_hash, transactions, timestamp=None):
[Link] = index
self.previous_hash = previous_hash
[Link] = timestamp or [Link]()
[Link] = transactions
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = [Link]({
"index": [Link],
"previous_hash": self.previous_hash,
"timestamp": [Link],
"transactions": [Link]
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
self.transaction_pool = []
[Link] = set()
def create_genesis_block(self):
23
return Block(0, "0", ["Genesis Block"])
def get_latest_block(self):
return [Link][-1]
def add_transaction(self, sender, receiver, amount):
transaction = {
"sender": sender,
"receiver": receiver,
"amount": amount
self.transaction_pool.append(transaction)
def mine_block(self):
if not self.transaction_pool:
print("No transactions to mine.\n")
return
latest = self.get_latest_block()
block = Block(
index=[Link] + 1,
previous_hash=[Link],
transactions=self.transaction_pool
)
[Link](block)
self.transaction_pool = []
print(f"Block mined: {[Link]}\n")
def register_node(self, address):
parsed = urlparse(address)
if [Link]:
[Link]([Link])
elif [Link]:
[Link]([Link])
24
else:
raise ValueError("Invalid node URL")
print(f"Node registered: {address}\n")
def print_nodes(self):
print("Registered Nodes:")
for node in [Link]:
print(node)
if __name__ == "__main__":
blockchain = Blockchain()
blockchain.register_node("[Link]
blockchain.register_node("[Link]
blockchain.register_node("[Link]
blockchain.print_nodes()
25
Output:
26
Program – 12
Write a Python Program to Validate a Blockchain by Checking Hash Integrity
import hashlib
import json
import time
class Block:
def __init__(self, index, previous_hash, data, timestamp=None):
[Link] = index
self.previous_hash = previous_hash
[Link] = timestamp or [Link]()
[Link] = data
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = [Link]({
"index": [Link],
"previous_hash": self.previous_hash,
"timestamp": [Link],
"data": [Link]
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "0", "Genesis Block")
def get_latest_block(self):
return [Link][-1]
def add_block(self, data):
27
prev_block = self.get_latest_block()
new_block = Block(prev_block.index + 1, prev_block.hash, data)
[Link](new_block)
print(f"Block {new_block.index} added.\n")
def is_valid(self):
for i in range(1, len([Link])):
current = [Link][i]
previous = [Link][i - 1]
if [Link] != current.calculate_hash():
print(f"Block {[Link]} hash mismatch!\n")
return False
if current.previous_hash != [Link]:
print(f"Block {[Link]} previous hash mismatch!\n")
return False
print("Blockchain is valid.\n")
return True
if __name__ == "__main__":
bc = Blockchain()
bc.add_block("First block data")
bc.add_block("Second block data")
bc.is_valid()
28
Output:
29