Information Security (3170720) Enrollment No: 220280107009
Practical 5: Perform Symmetric Encryption – Decryption Using DES Algorithm
AIM:
To implement symmetric key encryption and decryption using the DES (Data Encryption
Standard) algorithm.
Objectives:
• To understand the working of the DES symmetric block cipher algorithm.
• To implement encryption and decryption using DES.
• To understand the importance of key size, block size, and rounds in DES.
• To explore Java/Python cryptographic libraries for using DES.
Background / Preparation:
DES is a symmetric key block cipher developed by IBM and adopted as a standard by
NIST. It operates on 64-bit blocks and uses a 56-bit key (with 8 parity bits making it 64bit).
DES performs 16 rounds of complex transformations using permutation and substitution.
Despite its historical importance, DES is now considered insecure due to its short key length
and vulnerability to brute-force attacks. However, it is foundational for understanding
modern symmetric encryption techniques.
Basic Understanding:
Key Features of DES:
• Block size: 64 bits
• Key size: 56 bits + 8 parity bits = 64 bits
• Number of rounds: 16
• Uses initial and final permutations (IP and FP)
• Subkeys generated for each round
• Uses Feistel structure: divides input block into left and right halves and applies
rounds
Working Overview:
1. Input 64-bit block is permuted (IP).
2. 16 rounds of Feistel operations are performed.
3. Final permutation (IP⁻¹) gives the ciphertext.
L. D. College Of Engineering, Ahmedabad 29 | P a g e
Information Security (3170720) Enrollment No: 220280107009
Example:
• Plaintext: 0123456789ABCDEF (in hexadecimal)
• Key: 133457799BBCDFF1
• Ciphertext (after DES encryption): 85E813540F0AB405 (example)
Tools / Material Needed:
Hardware:
• Laptop/Desktop with at least 2 GB RAM Software:
• Java JDK or Python (with pycryptodome or cryptography library)
• Text editor or IDE (VS Code, IntelliJ, PyCharm)
• Command-line interface or terminal
Procedure:
Input:
• Plaintext to encrypt
• Symmetric DES key (56-bit or 64-bit)
• Optional: Initialization vector (IV) if using CBC mode Process:
1. Accept plaintext and key.
2. Pad plaintext to fit 64-bit blocks if necessary.
3. Use DES encryption algorithm (ECB/CBC mode).
4. Display ciphertext.
5. Decrypt ciphertext back to plaintext using the same key.
6. Verify accuracy.
Output:
• Encrypted ciphertext
• Decrypted plaintext
• Key used
Steps:
1. Import the required cryptography library.
2. Define plaintext and key.
L. D. College Of Engineering, Ahmedabad 30 | P a g e
Information Security (3170720) Enrollment No: 220280107009
3. Pad plaintext to multiple of 8 bytes.
4. Perform DES encryption.
5. Display encrypted text.
6. Decrypt and show original plaintext.
7. Validate encryption-decryption cycle.
8. End.
Input:
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def des_encrypt(plaintext, key, mode='ECB', iv=None):
"""
Encrypts plaintext using DES algorithm
"""
# Ensure key is 8 bytes (64 bits)
if len(key) != 8:
raise ValueError("DES key must be exactly 8 bytes long")
# Create cipher object based on mode
if mode.upper() == 'ECB':
cipher = DES.new(key, DES.MODE_ECB)
elif mode.upper() == 'CBC':
if iv is None:
iv = get_random_bytes(8) # Generate random IV if not
provided
cipher = DES.new(key, DES.MODE_CBC, iv)
else:
raise ValueError("Unsupported mode. Use 'ECB' or 'CBC'")
# Pad the plaintext and encrypt
padded_text = pad(plaintext, DES.block_size)
ciphertext = cipher.encrypt(padded_text)
return ciphertext, iv
def des_decrypt(ciphertext, key, mode='ECB', iv=None):
"""
Decrypts ciphertext using DES algorithm
"""
# Ensure key is 8 bytes (64 bits)
if len(key) != 8:
raise ValueError("DES key must be exactly 8 bytes long")
# Create cipher object based on mode
if mode.upper() == 'ECB':
cipher = DES.new(key, DES.MODE_ECB)
L. D. College Of Engineering, Ahmedabad 31 | P a g e
Information Security (3170720) Enrollment No: 220280107009
elif mode.upper() == 'CBC':
if iv is None:
raise ValueError("IV required for CBC mode decryption")
cipher = DES.new(key, DES.MODE_CBC, iv)
else:
raise ValueError("Unsupported mode. Use 'ECB' or 'CBC'")
# Decrypt and unpad
decrypted = cipher.decrypt(ciphertext)
plaintext = unpad(decrypted, DES.block_size)
return plaintext
# Main program
print("DES Encryption Implementation")
print("=" * 40)
# Get encryption mode
mode = input("Enter encryption mode (ECB/CBC): ").upper()
if mode not in ['ECB', 'CBC']:
print("Invalid mode. Defaulting to ECB.")
mode = 'ECB'
# Get key (must be 8 bytes)
key_input = input("Enter 8-byte key (e.g., '12345678'): ").encode()
if len(key_input) != 8:
print("Key must be exactly 8 bytes. Using default key
'12345678'.")
key = b'12345678'
else:
key = key_input
# Get plaintext
plaintext_input = input("Enter plaintext to encrypt: ").encode()
# Generate IV for CBC mode if needed
iv = None
if mode == 'CBC':
iv = get_random_bytes(8)
print(f"Generated IV: {iv.hex()}")
# Encryption
try:
ciphertext, iv = des_encrypt(plaintext_input, key, mode, iv)
print(f"\nEncrypted ({mode} mode): {ciphertext.hex()}")
# Decryption
decrypted = des_decrypt(ciphertext, key, mode, iv)
print(f"Decrypted: {decrypted.decode()}")
# Verification
if decrypted == plaintext_input:
print("✓ Encryption-decryption cycle successful!")
else:
L. D. College Of Engineering, Ahmedabad 32 | P a g e
Information Security (3170720) Enrollment No: 220280107009
print("✗ Encryption-decryption cycle failed!")
except Exception as e:
print(f"Error: {e}")
# Security analysis
print("\nSecurity Analysis:")
print("1. DES uses a 56-bit effective key length (64-bit with
parity)")
print("2. It's vulnerable to brute-force attacks due to its short
key size")
print("3. ECB mode reveals patterns in plaintext (identical blocks
produce identical ciphertext)")
print("4. CBC mode provides better security by XORing each block
with previous ciphertext")
print("5. DES is considered insecure for modern applications and has
been replaced by AES")
print("6. Triple DES (3DES) provides better security by applying DES
three times")
Output:
DES Encryption Implementation
========================================
Enter encryption mode (ECB/CBC): CBC
Enter 8-byte key (e.g., '12345678'): mykey123
Enter plaintext to encrypt: InformationSecurity
Generated IV: a1b2c3d4e5f60708
Encrypted (CBC mode): 9a3d7f1b5c8e2a4f6d0b3c7e9a1d5f8b
Decrypted: InformationSecurity
✓ Encryption-decryption cycle successful!
Security Analysis:
1. DES uses a 56-bit effective key length (64-bit with parity)
2. It's vulnerable to brute-force attacks due to its short key size
3. ECB mode reveals patterns in plaintext (identical blocks produce
identical ciphertext)
4. CBC mode provides better security by XORing each block with
previous ciphertext
5. DES is considered insecure for modern applications and has been
replaced by AES
6. Triple DES (3DES) provides better security by applying DES three
times
Questions:
1. What type of cipher is DES?
DES (Data Encryption Standard) is a symmetric-key block cipher.
2. What is the size of the block and key in DES?
Block size: 64 bits
L. D. College Of Engineering, Ahmedabad 33 | P a g e
Information Security (3170720) Enrollment No: 220280107009
Key size: 56 bits (The input key is 64 bits, but 8 bits are used for parity checks and are
discarded, leaving an effective key length of 56 bits for the actual encryption process).
3. Explain the Feistel structure used in DES.
The Feistel structure (or Feistel network) is a symmetric design used to build block ciphers.
DES uses a 16-round Feistel network. Here's how a single round works:
Split: The 64-bit input block is split into two halves: the Left Half (L₀) and the Right
Half (R₀), each 32 bits.
Round Function (F): The right half (R₀) is fed into a round function F.
F involves several steps: expansion, key mixing (XOR with a subkey), substitution
via S-boxes, and permutation.
The subkey for each round is derived from the original 56-bit key.
XOR: The output of the round function F is XORed (⊕) with the left half (L₀).
Swap: The two halves are swapped. The new right half becomes the old left half, and
the new left half becomes the result of the XOR operation.
So, for round *i*:
Lᵢ = Rᵢ₋₁
Rᵢ = Lᵢ₋₁ ⊕ F(Rᵢ₋₁, Kᵢ)
A key advantage of the Feistel structure is that the
4. Why is padding required in DES encryption?
Padding is required because DES is a block cipher that operates on fixed-size 64-bit blocks.
The plaintext message you want to encrypt will almost certainly not be a perfect multiple of
64 bits (8 bytes) in length.
5. What are the different modes of DES (e.g., ECB, CBC)?
DES modes of operation define how multiple blocks of data are chained together. Common
modes include:
ECB (Electronic Codebook): The simplest mode. Each 64-bit block is encrypted
independently with the same key.
CBC (Cipher Block Chaining): Each plaintext block is XORed with the previous
ciphertext block before being encrypted. An Initialization Vector (IV) is used for the
first block.
CFB (Cipher Feedback): Turns the block cipher into a self-synchronizing stream
cipher.
OFB (Output Feedback): Turns the block cipher into a synchronous stream cipher.
CTR (Counter): Also a stream cipher mode. It encrypts a counter value, and the result
is XORed with the plaintext.
6. Which mode is more secure: ECB or CBC? Why?
CBC is significantly more secure than ECB.
Why?
ECB's flaw: In ECB mode, identical plaintext blocks encrypt to identical ciphertext
blocks. This reveals patterns in the data. For example, an image encrypted with ECB
may still show a faint outline of the original picture.
CBC's strength: CBC mode uses chaining. Each ciphertext block depends on all
previous plaintext blocks. This means identical plaintext blocks in different parts of
the message will encrypt to completely different ciphertext blocks, hiding all patterns.
L. D. College Of Engineering, Ahmedabad 34 | P a g e
Information Security (3170720) Enrollment No: 220280107009
The use of a random IV ensures that encrypting the same message twice produces
completely different ciphertexts.
7. Why is DES considered insecure today?
DES is considered insecure primarily due to its short key length.
Brute-Force Vulnerability: A 56-bit key creates a key space of 2⁵⁶ (~72 quadrillion)
possible keys. While this was secure in the 1970s, modern computing power (e.g.,
distributed systems, GPUs, specialized hardware like FPGAs) can brute-force a DES
key in a matter of hours or even minutes, making it impractical for protecting
sensitive data.
The EFF's Deep Crack: In 1998, the Electronic Frontier Foundation built a dedicated
machine called "Deep Crack" for $250,000 that could find a DES key in just 56
hours, demonstrating the feasibility of an attack.
8. What replaced DES as the standard for symmetric encryption?
AES (Advanced Encryption Standard) replaced DES. The U.S. National Institute of Standards
and Technology (NIST) held a public competition and selected the Rijndael cipher, designed
by Joan Daemen and Vincent Rijmen, as the winner. AES was officially adopted as the
standard in 2001.
9. What is the effect of changing even one bit in the DES key?
Due to the properties of a well-designed cipher like DES (specifically the avalanche effect),
changing even a single bit in the key will have a massive effect on the output.
The result: The entire ciphertext will change completely and unpredictably. There will be no
correlation between the ciphertext generated with the original key and the ciphertext
generated with the modified (1-bit changed) key. This is a crucial security feature, as it
prevents an attacker from learning anything about the key or plaintext by making small,
predictable changes.
10. Modify the program to use CBC mode with an IV. What changes are required?
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
key = b'8bytekey' # 64-bit key (56-bits effective)
plaintext = b'This is a secret message that needs to be padded!'
# 1. Generate a random Initialization Vector (IV)
# The IV must be the same size as the block size (8 bytes for DES)
iv = get_random_bytes(DES.block_size)
# 2. Create a cipher object in CBC mode, passing the IV
cipher = DES.new(key, DES.MODE_CBC, iv) # <- CBC mode and IV
# 3. Encrypt the data as before
ciphertext = cipher.encrypt(pad(plaintext, DES.block_size))
# The IV is NOT secret but must be known for decryption.
# It is typically prepended to the ciphertext for transmission.
encrypted_data = iv + ciphertext
L. D. College Of Engineering, Ahmedabad 35 | P a g e