as part of a course on Information Security I am implementing simple forms of encryption, in this case the shift cipher. I created a simple function to perform the encryption on plaintext and return the ciphertext.
function ciphertext = encrypt(plaintext, k)
%first, call the "double" function on the plaintext
%this converts it to numbers for ASCII usage
%we add k to all these numbers
asciivec = double(plaintext);
for i = 1:length(asciivec)
if (asciivec(i) + k) > 90
diff = (asciivec(i) + k) - 90;
adjustedvec(i) = 64 + diff;
else
adjustedvec(i) = asciivec(i) + k;
end
end
%vector is adjusted, convert back to characters
ciphertext = char(adjustedvec);
return
When I call this is main, the output is all wrong. If I feed it a character vector such as ‘testing’, it should return a vector in the format of ‘xxxxxxx’ adjusted by the proper k according to the cipher, however the actual result ends up being as such:
ciphertext =
7x7 char array
‘x ‘
‘x ‘
‘x ‘
‘x ‘
‘x ‘
‘x ‘
‘x ‘
This does not occur when I run the function as a standalone script, only when I run it as a function.
I turned the function into a standalone program and hardcoded the inputs, with both being in the same format as in main. When I did this, the function worked properly and the result of ciphertext was a char vector as expected. So why does this work alone and not in main?
Main below
clc
plaintext = 'SSOEATBENEDUMHALLOHARASTREET';
k = 3;
secrets = encrypt(plaintext, k);
arm618 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1