KEMBAR78
Cryptography and Blockchain Security Lab Manual | PDF | Key (Cryptography) | Encryption
0% found this document useful (0 votes)
48 views45 pages

Cryptography and Blockchain Security Lab Manual

The document is a lab manual for a Diploma in Blockchain Technology, focusing on Cryptography and Blockchain Security. It includes practical exercises on symmetric encryption, digital signature verification, blockchain transaction simulation, and hash function implementation. Each practical outlines objectives, theory, tools required, procedures, sample code, observations, results, and conclusions.

Uploaded by

Jatin Patel
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)
48 views45 pages

Cryptography and Blockchain Security Lab Manual

The document is a lab manual for a Diploma in Blockchain Technology, focusing on Cryptography and Blockchain Security. It includes practical exercises on symmetric encryption, digital signature verification, blockchain transaction simulation, and hash function implementation. Each practical outlines objectives, theory, tools required, procedures, sample code, observations, results, and conclusions.

Uploaded by

Jatin Patel
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/ 45

Centre of Distance and Online Education

Subject: Cryptography and Blockchain Security


Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

DUAL DEGREE PROGRAM

CRYPTOGRAPHY AND BLOCKCHAIN SECURITY

SEMESTER 2

DIPLOMA IN BLOCKCHAIN TECHNOLOGY

LAB MANUAL

pg. 1 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Certificate
This is to certify that

Mr. Jatin Patel

Enrolment Number 2422759060034 of Semester 01

has completed Lab Manual work of 10 Practical

for the subject - CRYPTOLOGY AND BLOCKCHAIN SECURITY

During the academic year 2024-25

Date of Submission:

Signature Signature Signature

(Student) (Subject Teacher) (Director)

pg. 2 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical Title

1. Encryption and Decryption using Symmetric Encryption


2. Digital Signature Verification using RSA or ECDSA
3. Blockchain Transaction Simulation
4. Hash Function Implementation (SHA-256 and MD5)
5. Smart Contract Development using Solidity and Remix IDE
6. Ethereum Wallet Creation and Management using MetaMask
7. Smart Contract Deployment on Local Blockchain using Ganache and Truffle
8. Blockchain-Based Voting System Simulation
9. Decentralized File Storage using IPFS
10. Cybersecurity Attack and Defense Simulation (Brute-force, MITM, etc.)

pg. 3 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 1: Encryption and Decryption using Symmetric Encryption

Objective: Implement a program to encrypt and decrypt messages using symmetric encryption
algorithms like AES or DES.

Theory: Encryption converts plain text into unreadable cipher text using a key, and decryption
converts it back to the original form. Symmetric encryption uses the same key for both
encryption and decryption. AES (Advanced Encryption Standard) and DES (Data Encryption
Standard) are common symmetric algorithms. AES is more secure and widely used due to its
stronger key sizes (128, 192, or 256 bits).

Tools Required:

• Python 3.x

• pycryptodome or cryptography library

• Text editor or IDE

Procedure:

1. Install pycryptodome using pip: pip install pycryptodome

2. Write a program to encrypt and decrypt a message using AES.

Sample Code:

from Crypto.Cipher import AES

from Crypto.Random import

get_random_bytes import base64

def pad(text):

while len(text) % 16 != 0:

text += ' '

return text

pg. 4 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

key = get_random_bytes(16)

cipher = AES.new(key, AES.MODE_CBC)

message = pad("This is a secret message.")

ciphertext = cipher.encrypt(message.encode('utf-8'))

print("Cipher Text:", base64.b64encode(ciphertext))

cipher_dec = AES.new(key, AES.MODE_CBC, cipher.iv)

decrypted = cipher_dec.decrypt(ciphertext).decode('utf-8').strip()

print("Decrypted Text:", decrypted)

Observations:

• The same key must be used for encryption and decryption.

• The output ciphertext changes with a different IV.

Result: The encryption and decryption of a message using AES was successfully implemented.

Conclusion: Symmetric encryption is fast and efficient for securing messages when the key is
securely shared.

Viva Questions:

1. What is symmetric encryption?

2. How is AES different from DES?

3. What is padding in encryption?

4. Why is IV important?

5. What are the limitations of symmetric encryption?

Practical 2: Digital Signature Verification using RSA or ECDSA

pg. 5 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Objective: Write a code to verify the authenticity and integrity of a digital signature using RSA
or ECDSA.

Theory: A digital signature ensures the integrity and authenticity of a message. RSA and ECDSA
are asymmetric cryptographic algorithms used for signing and verification. The private key is
used to sign, and the public key is used to verify.

Tools Required:

• Python 3.x

• cryptography or rsa library

Procedure:

1. Generate RSA keys.

2. Sign a message using the private key.

3. Verify the message using the public key.

Sample Code:

import rsa

# Key Generation

(pub_key, priv_key) = rsa.newkeys(512)

message = b"Verify this message"

pg. 6 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

signature = rsa.sign(message, priv_key, 'SHA-256')

# Verification

try:

rsa.verify(message, signature, pub_key)

print("Signature is valid.")

except:

print("Signature is invalid.")

Observations:

• The signature is unique to the message and private key.

• A change in the message or key results in verification failure.

Result: Successfully verified a digital signature using RSA.

Conclusion: Digital signatures are crucial for ensuring data integrity and authenticity.

pg. 7 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 2: Digital Signature Verification using Asymmetric Encryption

Objective:

To write a program to verify the authenticity and integrity of a digital signature using
asymmetric encryption algorithms like RSA or ECDSA.

Theory:

A digital signature is a mathematical scheme used to validate the authenticity and integrity of a
message, software, or digital document.

• Asymmetric Encryption uses a public key and a private key.

• The sender signs the message using their private key.

• The receiver verifies the message using the sender’s public

key. Popular Algorithms:

• RSA (Rivest-Shamir-Adleman) – widely used in secure data transmission.

• ECDSA (Elliptic Curve Digital Signature Algorithm) – faster and more efficient for
devices with limited computing power.

Key Benefits:

• Ensures authentication (message came from the claimed sender)

pg. 8 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Maintains integrity (message has not been altered)

Tools Required:

• Python 3.x

• cryptography or pycryptodome library

• IDE or terminal

Procedure:

1. Generate RSA key pair.

2. Create a hash of the message.

3. Sign the hash using the private key.

4. Verify the signature using the public key.

Sample Code (Using RSA and cryptography):

python

CopyEdit

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

from cryptography.hazmat.primitives import hashes, serialization

from cryptography.hazmat.backends import default_backend

# 1. Generate RSA Key Pair

pg. 9 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

public_key = private_key.public_key()

# 2. Message to be signed

message = b'Hello, this is a digitally signed message.'

# 3. Sign the message

signature = private_key.sign(

message,

padding.PSS(

mgf=padding.MGF1(hashes.SHA256()),

salt_length=padding.PSS.MAX_LENGTH

),

hashes.SHA256()

print("Signature generated.")

# 4. Verify the signature

try:

public_key.verify(

signature,

message,

pg. 10 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

padding.PSS( mgf=padding.MGF1(hashes.S

HA256()),

salt_length=padding.PSS.MAX_LENGTH

),

hashes.SHA256()

print("Signature verified. The message is authentic.")

except:

print("Signature verification failed.")

Observations:

• A digital signature was created using the private key.

• The signature was successfully verified using the corresponding public key.

• Changing the message would cause the verification to fail.

Result:

Successfully implemented a digital signature verification program using RSA. The system
correctly authenticated and validated the integrity of the message.

Conclusion:

Digital signatures are essential in cybersecurity for verifying authenticity and preventing
tampering. RSA provides a reliable method for signing and verifying messages.

pg. 11 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 3: Blockchain Transaction

Simulation Objective:

Develop a simple blockchain transaction simulation program that demonstrates the process of
creating and validating transactions in a blockchain network.

Theory:

A blockchain is a decentralized digital ledger that stores data across a distributed network of
computers. Each new entry (called a “block”) contains a set of transactions and is
cryptographically linked to the previous block, forming a chain.

In a simplified blockchain simulation:

• Transactions contain sender, receiver, and amount.

• Blocks contain a group of transactions, a timestamp, a hash, and a link to the


previous block’s hash.

pg. 12 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Hashing secures the data and ensures immutability.

• Optional components like Proof-of-Work can be included to mimic real-world


block mining.

This simulation helps you understand the foundational structure of blockchain technology and
how it maintains data integrity and security.

Tools Required:

• Python 3.x

• IDE or text editor (e.g., PyCharm, VS Code)

• Standard Python libraries (hashlib, time)

Procedure:

1. Create a Transaction class that holds sender, receiver, and amount.

2. Create a Block class that includes index, timestamp, transaction list, previous hash,
and current hash.

3. Define a Blockchain class to manage the chain of blocks.

4. Add methods to create a genesis block and to add new blocks.

5. Display the blockchain contents.

Sample Code:

python

CopyEdit

pg. 13 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

import hashlib

import time

class Transaction:

def init (self, sender, receiver, amount):

self.sender = sender

self.receiver = receiver

self.amount = amount

class Block:

def init (self, index, transactions, timestamp, previous_hash):

self.index = index

self.transactions = transactions

self.timestamp = timestamp

self.previous_hash = previous_hash

self.hash = self.calculate_hash()

def calculate_hash(self):

data = str(self.index) + str(self.timestamp) + str([vars(tx) for tx in self.transactions]) +


self.previous_hash

return hashlib.sha256(data.encode()).hexdigest()

class Blockchain:

def init (self):

self.chain = [self.create_genesis_block()]

pg. 14 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

def create_genesis_block(self):

return Block(0, [], time.time(), "0")

def get_latest_block(self):

return self.chain[-1]

def add_block(self, transactions):

latest_block = self.get_latest_block()

new_block = Block(len(self.chain), transactions, time.time(), latest_block.hash)

self.chain.append(new_block)

# Simulate transactions and blocks

blockchain = Blockchain()

transactions = [Transaction("Alice", "Bob", 100), Transaction("Bob", "Charlie", 50)]

blockchain.add_block(transactions)

# Display the blockchain

for block in blockchain.chain:

print("Block Index:", block.index)

print("Timestamp:", block.timestamp)

print("Transactions:", [vars(tx) for tx in block.transactions])

print("Previous Hash:", block.previous_hash)

pg. 15 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

print("Current Hash:",

block.hash) print("-" * 50)

Observations:

• Each block includes its own hash and the previous block’s hash, ensuring
tamper resistance.

• Changing any part of a transaction alters the block hash, breaking the chain.

• This simple blockchain doesn't use consensus algorithms like Proof-of-Work but
still demonstrates core concepts.

Result:

A basic blockchain simulation was successfully implemented. Transactions were securely


grouped into blocks, and each block was cryptographically linked to maintain data integrity.

Conclusion:

This practical provides a fundamental understanding of how blockchain secures data through
linked blocks and hashing. It serves as a foundational concept for more advanced topics like
consensus algorithms, smart contracts, and distributed networks.

pg. 16 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 4: Hash Function Implementation

Objective:

Implement a cryptographic hash function such as SHA-256 or MD5 to generate hash values for
given inputs and demonstrate collision resistance.

Theory:

pg. 17 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

A hash function is a mathematical function that converts an input (or “message”) into a fixed-
size string of bytes. The output is called a hash or digest. Cryptographic hash functions are
widely used in digital signatures, message integrity checks, and blockchain.

Key Properties of Cryptographic Hash Functions:

• Deterministic: Same input always produces the same hash.

• Fast computation: Hash is computed quickly.

• Pre-image resistance: Difficult to reverse a hash to find the original input.

• Collision resistance: No two inputs should produce the same hash.

• Avalanche effect: A small change in input drastically changes the output.

Common Algorithms:

• SHA-256: Secure Hash Algorithm 256-bit (used in Bitcoin, SSL, etc.)

• MD5: Message Digest 5 (faster but outdated and insecure for cryptographic use)

Tools Required:

• Python 3.x

• Standard libraries: hashlib

Procedure:

1. Write a Python program to take input from the user.

2. Apply both SHA-256 and MD5 to the input.

3. Display the resulting hash values.

pg. 18 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

4. Modify the input slightly and observe the hash changes.

5. Discuss the significance of collision resistance.

Sample Code:

python

CopyEdit

import hashlib

def hash_input(input_text):

sha256_hash = hashlib.sha256(input_text.encode()).hexdigest()

md5_hash = hashlib.md5(input_text.encode()).hexdigest()

return sha256_hash, md5_hash

# User input

text = input("Enter a message to hash: ")

sha256_val, md5_val = hash_input(text)

print("\nOriginal Text:", text)

print("SHA-256 Hash :",

sha256_val) print("MD5 Hash

:", md5_val)

# Slight modification

modified_text = text + "!"

sha256_mod, md5_mod = hash_input(modified_text)

pg. 19 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

print("\nModified Text:", modified_text)

print("SHA-256 Hash :", sha256_mod)

print("MD5 Hash :", md5_mod)

Observations:

• Even a minor change in input (like adding a punctuation mark) drastically changes
the hash.

• SHA-256 produces a 64-character hexadecimal hash.

• MD5 produces a 32-character hexadecimal hash.

• Hashes are irreversible—original messages cannot be retrieved from hash values.

Result:

The hash values were successfully generated using SHA-256 and MD5. It was observed that a
small change in input leads to completely different hash outputs, validating the avalanche effect
and collision resistance.

Conclusion:

Cryptographic hash functions like SHA-256 are essential for ensuring data integrity. They
provide a reliable mechanism to verify data without revealing the original content. Though MD5
is still used in some cases, it is vulnerable to collisions and should be avoided in security-critical
applications.

Practical 5: Smart Contract Development

pg. 20 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Objective:

To write, deploy, and test a basic smart contract using Solidity on the Ethereum blockchain
(test environment such as Remix IDE or Ganache).

Theory:

A smart contract is a self-executing program stored on a blockchain that automatically enforces


rules and executes actions when predefined conditions are met. These contracts eliminate the
need for intermediaries in transactions.

Key Features of Smart Contracts:

• Written in languages like Solidity (for Ethereum)

• Immutable once deployed on the blockchain

• Executed by the Ethereum Virtual Machine (EVM)

• Publicly accessible and verifiable

Popular Environments:

• Remix IDE: A web-based tool for writing, testing, and deploying Solidity contracts.

• Ganache: A local Ethereum blockchain for testing smart contracts.

• MetaMask: A browser extension for managing Ethereum wallets and interacting


with contracts.

Tools Required:

• Remix IDE (https://remix.ethereum.org/)

• Web3-compatible browser (Chrome with MetaMask)

• Internet connection

Procedure:

1. Open Remix IDE in your browser.

pg. 21 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

2. Create a new Solidity file (e.g., SimpleContract.sol).

3. Write a basic smart contract to store and retrieve a number.

4. Compile the contract using the Solidity compiler.

5. Deploy the contract using the JavaScript VM environment in Remix.

6. Interact with the deployed contract via the Remix GUI.

Sample Code (Solidity – Version ^0.8.0):

solidity

CopyEdit

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract SimpleStorage

{ uint public

storedNumber;

function set(uint _num) public

{ storedNumber = _num;

function get() public view returns (uint)

{ return storedNumber;

pg. 22 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Steps in Remix IDE:

1. Click on the “Solidity Compiler” tab → Select version 0.8.x → Compile the contract.

2. Go to the “Deploy & Run Transactions” tab:

o Environment: JavaScript VM

o Click “Deploy”

3. After deployment, test the contract:

o Use the set() function to store a number.

o Use the get() function to retrieve the number.

Observations:

• The contract was compiled and deployed successfully using Remix IDE.

• The set() function correctly updated the stored value.

• The get() function returned the exact stored value.

• Each interaction created a transaction on the simulated Ethereum environment.

Result:

A simple smart contract was developed, deployed, and tested successfully. The contract
correctly stored and retrieved a numerical value.

Conclusion:

Smart contracts allow decentralized, automated interactions on a blockchain. This practical


introduced Solidity programming, contract deployment, and interaction using Remix IDE,
forming a foundation for more advanced decentralized applications (DApps).

pg. 23 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 6: Ethereum Wallet Creation and Management

Objective:

To create and manage an Ethereum wallet using MetaMask, generate public/private key pairs,
and understand wallet functionalities.

Theory:

An Ethereum wallet is a digital tool that allows users to store and manage their Ethereum (ETH)
and interact with smart contracts on the Ethereum blockchain.

Types of Wallets:

• Hot Wallets: Connected to the internet (e.g., MetaMask, Trust Wallet)

• Cold Wallets: Offline wallets for added security (e.g., Ledger, Trezor)

MetaMask is a browser extension that functions as a crypto wallet and gateway to blockchain
apps (DApps). It allows users to:

• Generate Ethereum accounts

• Store private keys securely

• Send/receive ETH and tokens

• Interact with decentralized applications

Tools Required:

• Google Chrome or Firefox

• MetaMask browser extension

• Internet connection

pg. 24 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Procedure:

1. Install MetaMask:

o Visit https://metamask.io

o Download and install the extension for Chrome/Firefox

2. Create a New Wallet:

o Click "Get Started" → "Create a Wallet"

o Set a strong password

o Securely save the Secret Recovery Phrase (12 words)

3. View Wallet Details:

o View public address (starts with 0x...)

o Note that private key should never be shared

4. Switch to Test Networks:

o Enable test networks (e.g., Sepolia, Goerli) in settings

o Request test ETH from a faucet for experimentation

5. Send/Receive ETH:

o Use the “Send” button to transfer ETH

o Receive by copying the wallet address and sharing with sender

Observations:

• MetaMask securely generates and stores public/private key pairs.

• Wallets on test networks are useful for safe experimentation.

• The seed phrase is the only way to recover a lost wallet.

pg. 25 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Result:

An Ethereum wallet was successfully created and tested using MetaMask. ETH was sent and
received using public wallet addresses on a test network.

Conclusion:

MetaMask simplifies Ethereum wallet management, enabling secure storage, transaction


handling, and interaction with smart contracts and decentralized apps.

pg. 26 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 7: Smart Contract Deployment on Local Blockchain using Ganache

Objective:

To deploy and test a smart contract on a local Ethereum blockchain using Ganache and Truffle
Suite.

Theory:

Ganache is a local Ethereum blockchain simulator used for developing, testing, and deploying
smart contracts. It provides:

• Pre-funded test accounts

• Instant transaction confirmation

• Insight into gas usage and contract logs

Truffle Suite is a development framework for Ethereum that helps compile, migrate, and test
smart contracts.

Tools Required:

• Node.js and npm

• Ganache (GUI or CLI)

• Truffle framework

• MetaMask (optional for integration)

pg. 27 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Procedure:

1. Install Node.js and Truffle:

bash

CopyEdit

npm install -g truffle

2. Install Ganache:

o Download from https://trufflesuite.com/ganache

o Launch the application and create a new workspace

3. Initialize Truffle Project:

bash

CopyEdit

mkdir local-blockchain-project

cd local-blockchain-project

truffle init

4. Create Smart Contract:

o Save a contract file in contracts/SimpleStorage.sol

solidity

CopyEdit

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract SimpleStorage

{ uint public data;

pg. 28 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

function set(uint _val) public

{ data = _val;

function get() public view returns (uint)

{ return data;

5. Compile Contract:

bash

CopyEdit

truffle compile

6. Configure Ganache Network in truffle-config.js:

javascript

CopyEdit

module.exports = {

networks: {

development:

{ host:

"127.0.0.1",

port: 7545,

network_id: "*"

},

compilers: {

solc: {

pg. 29 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

version: "0.8.0"

};

7. Write Migration File (migrations/2_deploy_contracts.js):

javascript

CopyEdit

const SimpleStorage = artifacts.require("SimpleStorage");

module.exports = function (deployer) {

deployer.deploy(SimpleStorage);

};

8. Run Ganache and Deploy Contract:

o Open Ganache → Note port 7545

bash

CopyEdit

truffle migrate --network development

9. Interact Using Truffle Console:

bash

CopyEdit

truffle console --network development

let instance = await SimpleStorage.deployed()

instance.set(42)

let value = await instance.get()

pg. 30 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

console.log(value.toString())

Observations:

• Contract deployment on local network is fast and gas-free.

• Ganache shows transaction logs, block info, and account balances.

• Truffle simplifies compilation, migration, and testing workflows.

Result:

A smart contract was successfully deployed and tested on a local Ethereum blockchain using
Ganache and Truffle.

Conclusion:

Deploying on a local blockchain helps developers safely test and debug smart contracts before
deploying to live networks. This setup is ideal for rapid prototyping and DApp development.

pg. 31 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Practical 8: Blockchain-Based Voting System Simulation

Objective:

To simulate a secure and transparent voting system using blockchain technology and smart
contracts.

Theory:

Traditional voting systems are vulnerable to fraud, tampering, and lack transparency.
Blockchain-based voting systems solve these issues by offering:

• Decentralization – no central point of control

• Transparency – votes are visible on a public ledger

• Immutability – once recorded, votes cannot be changed

• Anonymity – voters' identities are hidden, but the vote is

counted A simple blockchain voting contract typically includes:

• A list of candidates

pg. 32 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• A voter registry

• Voting logic that restricts users to one vote

• Vote counting mechanism

Tools Required:

• Remix IDE (https://remix.ethereum.org/)

• MetaMask (optional, for real network interaction)

• Solidity

Procedure:

1. Open Remix IDE.

2. Create a new file: VotingSystem.sol.

3. Write a Solidity smart contract to manage candidates and voters.

4. Compile and deploy the contract using JavaScript VM.

5. Interact with the contract to cast votes and check results.

Sample Code (Solidity – Voting System):

solidity

CopyEdit

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract VotingSystem {

struct Candidate {

uint id;

pg. 33 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

string name;

uint voteCount;

address public electionCommission;

mapping(address => bool) public hasVoted;

mapping(uint => Candidate) public candidates;

uint public candidatesCount;

constructor() {

electionCommission = msg.sender;

addCandidate("Alice");

addCandidate("Bob");

function addCandidate(string memory _name) public {

require(msg.sender == electionCommission, "Only EC can add candidates");

candidatesCount++;

candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);

function vote(uint _candidateId) public { require(!

hasVoted[msg.sender], "Already voted");

require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate");

pg. 34 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

hasVoted[msg.sender] = true;

candidates[_candidateId].voteCount++;

function getVoteCount(uint _candidateId) public view returns (uint)

{ return candidates[_candidateId].voteCount;

Steps in Remix IDE:

1. Compile:

o Click the Solidity compiler tab

o Select version ^0.8.0

o Click “Compile VotingSystem.sol”

2. Deploy:

o Go to “Deploy & Run Transactions”

o Select Environment: JavaScript VM

o Click “Deploy”

3. Test the Contract:

o Call vote(1) from one account (vote for Alice)

o Call vote(2) from another account (vote for Bob)

o Try vote() again from same account – it should fail

o Use getVoteCount(1) and getVoteCount(2) to view vote counts

Observations:

pg. 35 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Voters were able to vote only once.

• Vote counts were updated correctly.

• Any duplicate voting attempt was rejected by the contract.

• Candidates could only be added by the election commission (contract deployer).

Result:

Successfully simulated a blockchain-based voting system that ensured only one vote per
address, transparent vote counts, and immutable voting records.

Conclusion:

Blockchain-based voting systems can significantly enhance the integrity, transparency, and
security of elections. This simulation demonstrates the core functionalities needed for such
systems using smart contracts.

Practical 9: Decentralized File Storage using IPFS

Objective:

To upload and retrieve files using IPFS (InterPlanetary File System), a decentralized protocol
for peer-to-peer file storage and sharing.

Theory:

IPFS is a distributed file system that allows users to store and access content using
content- addressing (via cryptographic hashes), instead of traditional location-based
addressing (like URLs).

pg. 36 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Key Characteristics of IPFS:

• Content-addressed: Files are retrieved by their hash (CID), not their location

• Decentralized: Files are stored across multiple nodes

• Immutable: Content cannot be changed without changing the hash

• Efficient: Eliminates duplication and supports distributed caching

IPFS Use Cases:

• Decentralized web hosting

• NFT metadata storage

• Blockchain-based dApps needing off-chain file storage

Tools Required:

• IPFS Desktop or Command Line (https://docs.ipfs.io)

• Optional: Web3.Storage or Pinata for pinning

• Internet connection

Procedure:

Option 1: Using IPFS Desktop

1. Download and install IPFS Desktop from https://docs.ipfs.io/install.

2. Launch the app and open the local IPFS node dashboard.

3. Drag and drop a file into the web interface to upload it.

4. Note the Content Identifier (CID) generated for the file.

5. Use the CID in a browser to retrieve the

file: arduino

CopyEdit

https://ipfs.io/ipfs/<your-cid>

pg. 37 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Option 2: Using Command Line

1. Install IPFS

CLI: bash

CopyEdit

npm install -g ipfs

ipfs init

ipfs daemon

2. Add a file:

bash

CopyEdit

echo "Hello from IPFS!" > sample.txt

ipfs add sample.txt

3. Note the CID and open:

arduino

CopyEdit

https://ipfs.io/ipfs/<CID>

Observations:

• Each uploaded file receives a unique hash (CID).

• Accessing the CID retrieves the exact original content.

• Changing the file changes its CID completely.

• Files stored on IPFS are not automatically permanent unless “pinned”.

pg. 38 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Result:

Files were successfully uploaded to IPFS, assigned content hashes, and retrieved using public
gateways.

Conclusion:

IPFS offers a powerful and decentralized method of storing and sharing files that complements
blockchain technology by handling large or off-chain data efficiently.

Practical 9: Decentralized File Storage using IPFS

Objective:

To upload and retrieve files using IPFS (InterPlanetary File System), a decentralized protocol
for peer-to-peer file storage and sharing.

pg. 39 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

Theory:

IPFS is a distributed file system that allows users to store and access content using
content- addressing (via cryptographic hashes), instead of traditional location-based
addressing (like URLs).

Key Characteristics of IPFS:

• Content-addressed: Files are retrieved by their hash (CID), not their location

• Decentralized: Files are stored across multiple nodes

• Immutable: Content cannot be changed without changing the hash

• Efficient: Eliminates duplication and supports distributed caching

IPFS Use Cases:

• Decentralized web hosting

• NFT metadata storage

• Blockchain-based dApps needing off-chain file storage

Tools Required:

• IPFS Desktop or Command Line (https://docs.ipfs.io)

• Optional: Web3.Storage or Pinata for pinning

• Internet connection

Procedure:

Option 1: Using IPFS Desktop

1. Download and install IPFS Desktop from https://docs.ipfs.io/install.

2. Launch the app and open the local IPFS node dashboard.

3. Drag and drop a file into the web interface to upload it.

4. Note the Content Identifier (CID) generated for the file.

pg. 40 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

5. Use the CID in a browser to retrieve the

file: arduino

CopyEdit

https://ipfs.io/ipfs/<your-cid>

Option 2: Using Command Line

1. Install IPFS

CLI: bash

CopyEdit

npm install -g ipfs

ipfs init

ipfs daemon

2. Add a file:

bash

CopyEdit

echo "Hello from IPFS!" > sample.txt

ipfs add sample.txt

3. Note the CID and open:

arduino

CopyEdit

https://ipfs.io/ipfs/<CID>

Observations:

• Each uploaded file receives a unique hash (CID).

• Accessing the CID retrieves the exact original content.

• Changing the file changes its CID completely.

pg. 41 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Files stored on IPFS are not automatically permanent unless “pinned”.

Result:

Files were successfully uploaded to IPFS, assigned content hashes, and retrieved using public
gateways.

Conclusion:

IPFS offers a powerful and decentralized method of storing and sharing files that complements
blockchain technology by handling large or off-chain data efficiently.

Practical 10: Cybersecurity Attack and Defense Simulation

Objective:

To simulate a basic cyber attack (e.g., brute-force login attempt or MITM attack) and
demonstrate mitigation techniques or defensive measures.

Theory:

Cybersecurity simulations help students understand:

• How attacks exploit vulnerabilities

• How to protect systems and networks

• Hands-on ethical hacking principles

Common Attack Vectors:

• Brute Force Attack: Repeatedly guessing passwords until successful

• Man-in-the-Middle (MITM): Intercepting communication between two parties

• SQL Injection: Injecting malicious SQL queries via user inputs

Defense Mechanisms:

• Rate-limiting, CAPTCHA

pg. 42 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Encryption (TLS/SSL)

• Input sanitization

• Two-factor authentication
⚠ Always perform security testing in a legal and ethical environment, such as virtual labs or
sandboxed test environments.

Tools Required:

• Python 3.x

• Virtual machine (e.g., Kali Linux)

• Wireshark or Burp Suite (for network monitoring)

• Flask (for simple web app)

• Optional: DVWA or Metasploitable for advanced testing

Procedure:

Simulating a Brute-Force Attack (Basic)

1. Create a login form using Flask:

python

CopyEdit

from flask import Flask, request

app = Flask( name )

USERNAME = "admin"

PASSWORD = "password123"

@app.route('/login', methods=['POST'])

pg. 43 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

def login():

if request.form['username'] == USERNAME and request.form['password'] == PASSWORD:

return "Login Successful"

return "Invalid Credentials"

app.run(debug=True)

2. Run the server:

bash

CopyEdit

python app.py

3. Create a brute-force attack script:

python

CopyEdit

import requests

url = 'http://localhost:5000/login'

usernames = ['admin']

passwords = ['123', 'admin', 'password', 'password123']

for pwd in passwords:

response = requests.post(url, data={'username': 'admin', 'password': pwd})

print(f"Trying password: {pwd} -> {response.text}")

Defensive Measure:

• Add CAPTCHA to the login form

• Lock account after multiple failed attempts

pg. 44 Enrollment: 2422759060034


Centre of Distance and Online Education
Subject: Cryptography and Blockchain Security
Course: Diploma in Blockchain Technology
Year: 1ST Semester: 2nd

• Monitor suspicious IP activity

Observations:

• The attacker script could guess weak passwords within seconds.

• Using strong passwords and implementing account lockout can stop brute-
force attempts.

• Monitoring tools like Wireshark can detect unauthorized requests.

Result:

A brute-force login attack was simulated, and defensive countermeasures such as input
restrictions and authentication rate-limiting were discussed.

Conclusion:

Understanding basic cyber attacks and implementing defense strategies is critical in securing
applications. Ethical simulations like this provide valuable insights into real-world cybersecurity
practices.

pg. 45 Enrollment: 2422759060034

You might also like