Pratice problem: Bob wants to send the message “Start sending messages at 8:30” to Alice in a secret way as an encrypted message. Write a program that encrypts and decrypts Bob's message. (Hint: Use the ASCII table) Two parts must be output: the encrypted information and the result of decryption of the encrypted information (Start sending messages at 8:30)
function [encrypted, decryptied] = exercise3(str, num)
%本函数利用凯撒密码解码译码机制,在输入待加密字符串后,自定义偏移位数
%可以输出加密前和解密后的信息
encrypted = str;
%字符串转化为ASCII码
ASCII_before = abs(str);
len = length(ASCII_before);
%将ASCII加1后转化为字符串输出
ASCII_after = zeros(1, len);
for i = 1:len
ASCII_after(i) = ASCII_before(i) + num;
%当原始文案中出现空格时,不进行转换(这里可写可不写)
if ASCII_before(i) == 32
ASCII_after(i) = 32;
end
end
decryptied = char(ASCII_after);
end
输出结果为
>> [encrypted, decryptied] = exercise3('Start sending messages at 8:30', 1)
encrypted =
'Start sending messages at 8:30'
decryptied =
'Tubsu tfoejoh nfttbhft bu 9;41'
>> [encrypted, decryptied] = exercise3('Start sending messages at 8:30', 2)
encrypted =
'Start sending messages at 8:30'
decryptied =
'Uvctv ugpfkpi oguucigu cv :<52'