create a single function in matlab that can both encrypt and decrypt a message u
ID: 3703040 • Letter: C
Question
create a single function in matlab that can both encrypt and decrypt a message using an auto-key cipher
1. Remove any special characters, punctuation and spaces from the message to be encoded.
2. Convert all lowercase letters to uppercase and use the 26-character alphabet used to create the encryption squares.
3. Generate the encryption/decryption key.
4. Encrypt/decrypt the message and output the result.
. 5. Decrypt the given message.
cannot use find function
must use loops and branching statements
Explanation / Answer
Encrypt
function cText = encrypt(pText, key)
v = vigenere;
exclude = regexp(pText, '[^a-zA-Z ]');
pText(exclude) = [];
key = lower(key) - double('a') + 1;
key(key < 0) = 27;
pText = lower(pText) - double('a') + 1;
pText(pText < 0) = 27;
keyIndex = mod(0:(numel(pText)-1), numel(key))+1;
k = key(keyIndex);
cText = arrayfun(@(m,n) v(m,n), k, pText) - 1;
cText(cText == 26) = double(' ') - double('a');
cText = upper(char(cText + double('a')));
decrypt
function pText = decrypt(cText, key)
v = vigenere;
key = lower(key) - double('a') + 1;
key(key < 0) = 27;
cText = lower(cText) - double('a') + 1;
cText(cText < 0) = 27;
keyIndex = mod(0:(numel(cText)-1), numel(key))+1;
k = key(keyIndex);
pText = arrayfun(@(m,n) find(v(m,:) == n), k, cText) - 1;
pText(pText == 26) = double(' ') - double('a');
pText = upper(char(pText + double('a')));
vigenere
function v = vigenere
count = 27;
alpha = 1:count;
v = arrayfun(@(n) circshift(alpha, [0, -n]), 0:count-1, ...
'UniformOutput', false);
v = reshape([v{:}], count, count);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.