Info
此问题已关闭。 请重新打开它进行编辑或回答。
Cesar cypher with wrap around for characters
1 次查看(过去 30 天)
显示 更早的评论
My question is as follows:
Write a function called caesar that accepts two arguments: the first is the character vector to be encrypted, while the second is the shift amount. The function returns the output argument coded, the encrypted text. The function needs to work with all the visible ASCII characters from space to ~. The ASCII codes of these are 32 through 126. If the shifted code goes outside of this range, it should wrap around. For example, if we shift ~ by 1, the result should be space. If we shift space by -1, the result should be ~
I tried many solutions and they turn out to be partially correct and the code fails when the character's ascii value exceeds 126 or falls below 32. I tried so hard and i have given up at this point. I will really appreciate it if anyone can give their version of the code so that i can interpret both and try to figure out where i went wrong.
the following is the code i tried:
function coded = caesar(stringg,shift_amt)
char_num = double(stringg);
encrypted_num = char_num + shift_amt;
for i = 1:length(encrypted_num)
if encrypted_num(1,i)>126
while encrypted_num(1,i)>126, encrypted_num(1,i) = abs(mod(encrypted_num(1,i),126)); end,
encrypted_num(1,i)=31+encrypted_num(1,i);
end
if encrypted_num(1,i)<32,
while encrypted_num(1,i)<32, encrypted_num(1,i) = abs(mod(encrypted_num(1,i),126));
end,
encrypted_num(1,i) = 127 - encrypted_num(1,i) ;
end
end
coded = char(encrypted_num);
4 个评论
Walter Roberson
2019-4-23
Jan:
Caeser Cipher is definitely out of bounds for open discussion under US law, which is based upon key size, not upon the fact that there are known techniques to solve the cipher.
Jan
2019-4-23
@Walter: I think, it is not correct to close the question based on this reason:
"Closure Reason: Not appropriate for MATLAB Answers - Due to the laws of the United States, it is not permitted to discuss Caeser Cypher without advance permission from the USA Department of Commerce."
The publishing of code for a strong encryption is not allowed, e.g. a 128 bit AES encryption. A Caesar cypher is not strong. As far as I remember I was asked, if I can limit the key length to 44 or 64 bit in my published AES code to be conform with the export restrictions. Of course a user could remove this restriction from the code easily. Nobody claimed, that these laws are useful.
回答(1 个)
Jan
2019-2-26
编辑:Jan
2019-2-26
See the mod() function.
char_num = double(stringg);
enc_num = char_num + shift_amt;
enc_num = mod(enc_num - 32, 126 - 32 + 1) + 32
The idea: Convert the data [32:126] to the range [0:126-32]. Then apply the shifting and use mod for the wrap around. Afterwards reconvert the data to the range [32:126].
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!