0% found this document useful (0 votes)
16 views12 pages

Activity 1 & 2 - Manual

This document contains 6 coding problems related to cryptography and information theory concepts. Problem 1 generates RSA public and private keys from prime numbers and encrypts/decrypts a message. Problem 2 implements a public key cryptosystem using AES encryption and decryption in MATLAB. Problem 3 generates a random AES key and encrypts/decrypts data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

Activity 1 & 2 - Manual

This document contains 6 coding problems related to cryptography and information theory concepts. Problem 1 generates RSA public and private keys from prime numbers and encrypts/decrypts a message. Problem 2 implements a public key cryptosystem using AES encryption and decryption in MATLAB. Problem 3 generates a random AES key and encrypts/decrypts data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ICC-21EC505

Activity 1
Name:__________________________ USN:_________________
1. Consider a source that generates symbols with the following probabilities:

Symbol Probability
A 0.4
B 0.3
C 0.2
D 0.1
Encode the sequence 'AABBCCDD' using the Huffman code using the Scilab platform.
Program:
Probabilities = [0.4, 0.3, 0.2, 0.1];
symbols = ['A', 'B', 'C', 'D'];
function [huffman_code, avg_length] = huffman(probabilities, symbols)
n = length(probabilities);
huffman_code = cell(1, n);
sorted_probs = probabilities;
sorted_symbols = symbols;
while length(sorted_probs) > 1
[sorted_probs, sorted_symbols] = sort_symbols(sorted_probs, sorted_symbols);
min1 = sorted_symbols{1};
min2 = sorted_symbols{2};
sorted_symbols = sorted_symbols(3:$);
for i = 1:length(min1)
huffman_code{min1(i)} = ['0', huffman_code{min1(i)}];
end
for i = 1:length(min2)
huffman_code{min2(i)} = ['1', huffman_code{min2(i)}];
end
combined_prob = sum(probabilities(min1)) + sum(probabilities(min2));
sorted_probs = [sorted_probs, combined_prob];
sorted_symbols = [sorted_symbols, {[min1, min2]}];
probabilities = [probabilities, combined_prob];
end
avg_length = 0;
for i = 1:n
avg_length = avg_length + probabilities(i) * length(huffman_code{i});
end
end
function [sorted_probs, sorted_symbols] = sort_symbols(probabilities, symbols)
[sorted_probs, idx] = gsort(probabilities);
sorted_symbols = symbols(idx);
end
sequence = 'AABBCCDD';
[huffman_code, avg_length] = huffman(probabilities, symbols);
encoded_sequence = '';
for i = 1:length(sequence)
idx = find(symbols == sequence(i));
encoded_sequence = [encoded_sequence, huffman_code{idx}];
end
disp('Huffman Code:');
disp(huffman_code);
disp('Encoded Sequence:');
disp(encoded_sequence);
disp('Average Length:');
disp(avg_length);
// The encoded sequence 'AABBCCDD'

2. Given the alphabet {A, B, C, D} with probabilities: P(A) = 0.4, P(B) = 0.3, P(C) = 0.2 & P(D) = 0.1
Encode the sequence 'AABBCCDD' using arithmetic coding using the Scilab platform.
// Define the probabilities
probabilities = [0.4, 0.3, 0.2, 0.1];
// Define the sequence to be encoded
sequence = "AABBCCDD";
// Initialize the range and cumulative probabilities
lower_bound = 0;
upper_bound = 1;
cumulative_prob = cumsum(probabilities);
// Encode the sequence
for i = 1:length(sequence)
symbol = sequence(i);
index = find(["A", "B", "C", "D"] == symbol);
% Calculate the new range
range = upper_bound - lower_bound;
upper_bound = lower_bound + range * cumulative_prob(index);
lower_bound = lower_bound + range * cumulative_prob(index - 1);
end
// Output the encoded value (average of the final range)
encoded_value = (upper_bound + lower_bound) / 2;
disp(encoded_value);
// This code will output the encoded value for the sequence 'AABBCCDD' using arithmetic coding.
3. Consider a source that generates symbols with the following frequencies:

Symbol Probability
A 40
B 30
C 20
Symbol Probability
D 10
Apply the Shannon-Fano-Elias coding algorithm to encode the symbol 'ABBACD' using the Scilab platform.
// Define the symbols and their probabilities
symbols = ["A", "B", "C", "D"];
probabilities = [40, 30, 20, 10];
// Sort symbols and probabilities in descending order of probabilities
[probabilities_sorted, indices] = gsort(probabilities, 'd');
symbols_sorted = symbols(indices);
// Define a function to generate Shannon-Fano codes recursively
function codes = generate_codes(symbols, probabilities, prefix)
n = length(symbols);
if n == 1
codes = struct(symbols, prefix);
else
% Find the split index
cumulative_prob = cumsum(probabilities);
split_index = find(cumulative_prob >= sum(probabilities)/2, 1, 'first');
% Generate codes recursively for left and right groups
left_symbols = symbols(1:split_index);
right_symbols = symbols(split_index+1:end);
left_probabilities = probabilities(1:split_index);
right_probabilities = probabilities(split_index+1:end);
left_codes = generate_codes(left_symbols, left_probabilities, prefix + "0");
right_codes = generate_codes(right_symbols, right_probabilities, prefix + "1");
% Merge left and right codes
codes = struct(left_codes, right_codes);
end
endfunction
// Generate Shannon-Fano codes
codes = generate_codes(symbols_sorted, probabilities_sorted, "");
// Encode the sequence 'ABBACD' using the generated codes
sequence = "ABBACD";
encoded_sequence = "";
for i = 1:length(sequence)
encoded_sequence = encoded_sequence + codes.(sequence(i));
end
disp(encoded_sequence);
// Encoded sequence for 'ABBACD' using Shannon-Fano-Elias coding algorithm.
4. Consider a (7, 4) Hamming code with the generator matrix:
G = [1 0 0 0 1 1 0
0100101
0010011
0 0 0 1 1 1 1]
Encode the message vector m = [1 0 1 1] using the given generator matrix the Scilab platform.
// Define the generator matrix
G = [1 0 0 0 1 1 0;
0 1 0 0 1 0 1;
0 0 1 0 0 1 1;
0 0 0 1 1 1 1];
// Define the message vector
m = [1 0 1 1];
// Encode the message using matrix multiplication
encoded_message = m * G;
disp(encoded_message);
// Encoded codeword: 1 1 1 1 0 1 0
5. Consider a (7,4) cyclic Hamming code with the generator polynomial: g(x) = 1+x2+x3
Determine the codeword for the message vector m= [1011].
// Define the message vector
m = [1 0 1 1];
// Define the generator polynomial coefficients
g = [1 0 1 1];
// Perform polynomial multiplication
c = gfconv(m, g);
// Extract the coefficients of the codeword polynomial
codeword = c.coeffs;
// Display the codeword
disp("Codeword:");
disp(codeword);
// Codeword C = [0 0 0 0 0 0 0].
6. Consider a (2,1) convolutional encoder circuit shown in the figure,
Fig. 6
Encode the message 11011101.
function encoded_message = convolutional_encode(message, G1, G2)
% Encodes the message 'message' using generator polynomials 'G1' and 'G2'
% Initialize shift registers
reg1 = zeros(1, K); % K = constraint length (replace with actual value)
reg2 = zeros(1, K);
encoded_message = [];
% Loop through each bit of the message
for i = 1:length(message)
% Shift registers
reg1 = shift_register(reg1, 1);
reg2 = shift_register(reg2, 1);
% Update registers with current bit
reg1(1) = message(i);
% Perform XOR operations based on generator polynomials
out1 = mod2_add(reg1, G1);
out2 = mod2_add(reg2, G2);
% Append output bits to encoded message
encoded_message = [encoded_message, out1(1), out2(1)];
end
end
// Encoded message: [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1]
Activity 2
Name:__________________________ USN:_________________
1. Using Matlab, take two prime numbers and then compute Public and Private keys. Then encrypt the
message using the public key and decrypt using Private key.
function [publicKey, privateKey] = generateKeys(p, q)
% Calculate modulus and phi(n)
n = p * q;
phi_n = (p - 1) * (q - 1);
% Choose a random public exponent (coprime with phi_n)
e = randi(phi_n - 1);
while gcd(e, phi_n) ~= 1
e = randi(phi_n - 1);
end
% Calculate the private exponent using modular inverse
d = modinv(e, phi_n);
% Public and private key pairs
publicKey = [e, n];
privateKey = [d, n];
end
function cipher = encrypt(message, publicKey)
% Extract public key components
e = publicKey(1);
n = publicKey(2);
% Encrypt the message using modular exponentiation
cipher = modpow(message, e, n);
end
function message = decrypt(cipher, privateKey)
% Extract private key components
d = privateKey(1);
n = privateKey(2);
% Decrypt the message using modular exponentiation
message = modpow(cipher, d, n);
end
% Example usage
p = 11;
q = 13;

[publicKey, privateKey] = generateKeys(p, q);


message = 'Hello!';
message_to_encode = uint8(message); % Convert message to numerical values
cipher = encrypt(message_to_encode, publicKey);
decrypted_message = decrypt(cipher, privateKey);
original_message = char(decrypted_message); % Convert numerical values back to characters
disp('Original message:', message);
disp('Encrypted message:', cipher);
disp('Decrypted message:', original_message);

2. Implement a public key cryptosystem using MATLAB with AES encryption and decryption.
function encrypted_data = aes_encrypt(data, key)
% Convert key and data to uint8 arrays
key = uint8(key);
data = uint8(data);
% Use Cipher object for AES encryption in CBC mode
cipher = Cipher('AES-256/CBC');
cipher.Key = key;
cipher.Mode = 'CBC';
encrypted_data = cipher.encrypt(data);
end
function decrypted_data = aes_decrypt(encrypted_data, key)
% Convert key and encrypted data to uint8 arrays
key = uint8(key);
encrypted_data = uint8(encrypted_data);
% Use Cipher object for AES decryption in CBC mode
cipher = Cipher('AES-256/CBC');
cipher.Key = key;
cipher.Mode = 'CBC';
decrypted_data = cipher.decrypt(encrypted_data);
end
3. Implementing the RSA algorithm in MATLAB for generating public and private keys, encrypting a
message, and decrypting the ciphertext.
function [publicKey, privateKey] = generateKeys(p, q)
% Calculate modulus and phi(n)
n = p * q;
phi_n = (p - 1) * (q - 1);

% Choose a random public exponent (coprime with phi_n)


e = randi(phi_n - 1);
while gcd(e, phi_n) ~= 1
e = randi(phi_n - 1);
end

% Calculate the private exponent using modular inverse


d = modinv(e, phi_n);

% Public and private key pairs


publicKey = [e, n];
privateKey = [d, n];
end
function cipher = encrypt(message, publicKey)
% Convert message to numerical values (ASCII)
message_to_encode = uint8(message);
% Extract public key components
e = publicKey(1);
n = publicKey(2);
% Encrypt the message using modular exponentiation
blocks = reshape(message_to_encode, [1, ceil(length(message_to_encode)/length(dec2bin(n-1))) *
length(dec2bin(n-1))]);
cipher = modpow(blocks, e, n);
end
function message = decrypt(cipher, privateKey)
% Extract private key components
d = privateKey(1);
n = privateKey(2);
% Decrypt the message using modular exponentiation
blocks = modpow(cipher, d, n);
message = char(reshape(blocks, [1, numel(blocks)]));
end
% Example usage
p = 17; % Replace with larger prime numbers for better security
q = 23;
[publicKey, privateKey] = generateKeys(p, q);
message = 'Hello, world!';
cipher = encrypt(message, publicKey);
decrypted_message = decrypt(cipher, privateKey);
disp('Original message:', message);
disp('Encrypted message:', cipher);
disp('Decrypted message:', decrypted_message);
4. Implement the Vigenère cipher encryption and decryption algorithm in MATLAB. Use the provided
functions to encrypt the message "HELLO" using the key "KEY".
a) Perform Vigenère encryption on the message "HELLO" using the key "KEY".
b) Decrypt the resulting ciphertext using the same key.
function cipherText = vigenere_encrypt(message, key)
% Convert message and key to uppercase characters
message = upper(message);
key = upper(key);
% Ensure key length matches message length (repeat key if needed)
key = repmat(key, ceil(length(message) / length(key)));
% Convert characters to numerical values (A=1, B=2, ..., Z=26)
message_num = double(message) - 64;
key_num = double(key) - 64;
% Perform Vigenère cipher using modular arithmetic
cipherText_num = mod(message_num + key_num - 1, 26) + 1;
% Convert numerical values back to characters
cipherText = char(cipherText_num + 64 - 1);
end
function message = vigenere_decrypt(cipherText, key)
% Convert cipherText and key to uppercase characters
cipherText = upper(cipherText);
key = upper(key);
% Ensure key length matches cipherText length (repeat key if needed)
key = repmat(key, ceil(length(cipherText) / length(key)));
% Convert characters to numerical values
cipherText_num = double(cipherText) - 64;
key_num = double(key) - 64;

% Perform Vigenère cipher decryption using modular arithmetic


message_num = mod(cipherText_num - key_num + 26, 26) + 1;
% Convert numerical values back to characters
message = char(message_num + 64 - 1);
end
% Example usage
message = 'HELLO';
key = 'KEY';
ciphertext = vigenere_encrypt(message, key);
decrypted_message = vigenere_decrypt(ciphertext, key);
disp('Original message:', message);
disp('Encrypted message:', ciphertext);
disp('Decrypted message:', decrypted_message);
// This code will output:
Original message: HELLO
Encrypted message: JGNPR
Decrypted message: HELLO
5. Implement the Playfair cipher encryption and decryption algorithm in MATLAB using the provided
functions. Encrypt the message "HELLO" using the key "PLAYFAIRKEY".
function cipherText = playfair_encrypt(message, key)
% Convert message and key to uppercase characters
message = upper(message);
key = upper(key);
% Remove duplicate letters from the key
key = unique(key, 'stable');
% Add remaining alphabets to the key square, excluding J
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';
for i = 1:length(alphabet)
if ~any(alphabet(i) == key)
key = [key alphabet(i)];
end
if length(key) == 25
break;
end
end

% Reshape the key into a 5x5 matrix


key_matrix = reshape(key, 5, 5);
% Handle double letters by inserting 'X'
message = insert_x(message);
% Group message into pairs and encrypt each pair
cipherText = '';
for i = 1:2:length(message)
pair = message(i:i+1);
[row1, col1] = find(key_matrix == pair(1));
[row2, col2] = find(key_matrix == pair(2));
if row1 == row2 % Same row, shift columns
cipherText = [cipherText key_matrix(row1, mod(col1+1, 5)+1) key_matrix(row2, mod(col2+1, 5)+1)];
elseif col1 == col2 % Same column, shift rows
cipherText = [cipherText key_matrix(mod(row1+1, 5)+1, col1) key_matrix(mod(row2+1, 5)+1, col2)];
else % Different row and column, swap positions
cipherText = [cipherText key_matrix(row1, col2) key_matrix(row2, col1)];
end
end
end
function message = playfair_decrypt(cipherText, key)
% Convert cipherText and key to uppercase characters
cipherText = upper(cipherText);
key = upper(key);
% Remove duplicate letters from the key
key = unique(key, 'stable');
% Add remaining alphabets to the key square, excluding J
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';
for i = 1:length(alphabet)
if ~any(alphabet(i) == key)
key = [key alphabet(i)];
end
if length(key) == 25
break;
end
end

% Reshape the key into a 5x5 matrix


key_matrix = reshape(key, 5, 5);
% Group ciphertext into pairs and decrypt each pair
message = '';
for i = 1:2:length(cipherText)
pair = cipherText(i:i+1);
[row1, col1] = find(key_matrix == pair(1));
[row2, col2] = find(key_matrix == pair(2));
if row1 == row2 % Same row, shift columns
message = [message key_matrix(row1, mod(col1-1, 5)+1) key_matrix(row2, mod(col2-1, 5)+1)];
elseif col1 == col2 % Same column, shift rows
message = [message key_matrix(mod(row1-1, 5)+1, col1) key_matrix(mod(row2-1, 5)+1, col2)];
else % Different row and column, swap positions
message = [message key_matrix(row1, col2) key_matrix(row2, col1)];
end
end
% Remove any inserted 'X'
message = remove_x(message);
end
function message = insert_x(message)
% Insert 'X' between duplicate letters
for i = 1:length(message)-1
if message(i) == message(i+1)
message = [message(1:i) 'X' message(i+1:end)];
end
end
end
function message = remove_x(message)
% Remove 'X' from the message
message = message(message ~= 'X');
end

You might also like