i am writting a code for Vigenere Cipher but i am troubled with a question that how could i repeat key as that of my text to be ciphered
7 次查看(过去 30 天)
显示 更早的评论
my code is given below but error is key length is not same as plain_text
% Matlab code to encipher and Decipher Vigenere Cipher
% input parameter
key = input('Enter the cipher key: ','s' );
plain_text =input('ENter the text to be ciphered: ','s');
length(plain_text)
k=repmat((key),1,length(plain_text))
%k1=k(:)'
%k=repelem(key,length(plain_text))
% Vigenere ciphere Encryption
plain_num=plain_text-97;
k1=k-97;
ciphered_num=rem(plain_num+k1,26);
ciphered_text=char(ciphered_num+97)
% Vigenere ciphere Decryption
ciphered_num=ciphered_text-97;
deciphered_num=rem(ciphered_num-k1,26);
deciphered_text=char(deciphered_num+97)
0 个评论
采纳的回答
Geoff Hayes
2017-3-3
mahnoor - the problem is with
k=repmat((key),1,length(plain_text))
You don't want to repeat the key for each letter of plain_text (unless the key is a single character) but you want to repeat it enough times so that the "extended" key has the same characters as the plain text. For example, if
key = 'logan';
plainText = 'superheromovies2017';
then the extended key would be
extendedKey = 'loganloganloganloga';
So your code will have to determine this. I suppose you could do something like
extendedKey = '';
if length(key) < length(plainText)
keyReps = floor(length(plainText)/length(key));
extendedKey = [repmat(key,1,keyReps) key(1:rem(length(plainText),length(key)))];
else
extendedKey = key(1:length(plainText));
end
This should give you the correct key, but you may want to step through the remainder of the code to ensure that it is doing what you expect.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Encryption / Cryptography 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!