Decrypting a message in matlab?
Afficher commentaires plus anciens
Im trying to decrypt a message in matlab. My code can decrypt some shorter messages with a low key, but when I try to decrypt a long message with like a key of 9 it wont work. I thought my code was correct, but I guess I have some flaw in it. Can anyone help? (Using ASCII values)
original_message=input('Please enter the message you want decrypted:', 's') % original message
key=input('What will be the encryption key you are using:')
number_message=double(original_message)
for k=1:length(original_message)
if number_message(k)>=65 && number_message(k)<=90
number_message(k)=number_message(k)-key
if number_message(k)<=90
number_message(k)=number_message(k)+26
end
elseif number_message(k)>=97 && number_message(k)<=122
number_message(k)=number_message(k)-key
if number_message(k)<=122
number_message(k)=number_message(k)+26
end
end
end
fprintf('The decrypted message is %s \n',number_message)
Réponse acceptée
Plus de réponses (1)
TastyPastry
le 30 Oct 2015
There are 3 things which don't work with your code:
- It doesn't work when the key is >26.
- Your checks for whether or not the values are letters are wrong. Currently, your code attempts to move the ASCII value back to the proper range 65-90, 97-122 when the letter is already within the range. Eg., if the current letter is b, value 66, it would get changed to \, value 92.
- The doesn't change the vector back to a string.
Here are the bits of code I would add/change:
number_message = char(number_message);
key=mod(key,26);
number_message(k)<=96
number_message(k)<=64
I'll leave where to put the replacements as an exercise to you.
Also, there are a lot of examples of Caesar ciphers written in MATLAB online. I would encourage you to look at those, since this is a common problem in most courses.
1 commentaire
Nick Haufler
le 30 Oct 2015
Modifié(e) : Nick Haufler
le 30 Oct 2015
Catégories
En savoir plus sur Encryption / Cryptography dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!