利用matlab,将下载的DES嵌入,并以分组密码OFB运行模式编写,并提供可用的DES代码,要求仅输入任意字符,即可输出加密后的字符和解密后的字符
时间: 2023-08-13 13:05:57 浏览: 47
以下是利用MATLAB实现DES嵌入和OFB模式的加密解密代码:
```matlab
% DES加密解密实现
% OFB模式
% 作者:AI学园
clc;
clear all;
% 设置密钥
key = '01234567';
% 设置初始向量
iv = 'abcdefgh';
% 加密函数
function [cipher_text] = des_encrypt(plain_text, key)
% 将明文转换为二进制
plain_text_bin = dec2bin(plain_text, 8);
plain_text_bin = reshape(plain_text_bin', 1, length(plain_text_bin(:)));
plain_text_bin = str2num(plain_text_bin(:))';
% 加密过程
cipher_text_bin = des(plain_text_bin, key, 'encrypt');
% 将密文转换为字符形式
cipher_text = char(bin2dec(reshape(num2str(cipher_text_bin), 8, [])'))';
end
% 解密函数
function [plain_text] = des_decrypt(cipher_text, key)
% 将密文转换为二进制
cipher_text_bin = dec2bin(cipher_text, 8);
cipher_text_bin = reshape(cipher_text_bin', 1, length(cipher_text_bin(:)));
cipher_text_bin = str2num(cipher_text_bin(:))';
% 解密过程
plain_text_bin = des(cipher_text_bin, key, 'decrypt');
% 将明文转换为字符形式
plain_text = char(bin2dec(reshape(num2str(plain_text_bin), 8, [])'))';
end
% OFB模式加密
function [cipher_text] = ofb_encrypt(plain_text, key, iv)
% 设置初始向量
iv_bin = dec2bin(iv, 8);
iv_bin = reshape(iv_bin', 1, length(iv_bin(:)));
iv_bin = str2num(iv_bin(:))';
% 加密过程
cipher_text = '';
for i = 1:length(plain_text)
% 生成密钥流
if i == 1
key_stream_bin = des(iv_bin, key, 'encrypt');
else
key_stream_bin = des(key_stream_bin, key, 'encrypt');
end
% 加密
plain_text_bin = dec2bin(plain_text(i), 8);
plain_text_bin = reshape(plain_text_bin', 1, length(plain_text_bin(:)));
plain_text_bin = str2num(plain_text_bin(:))';
cipher_text_bin = bitxor(plain_text_bin, key_stream_bin);
% 将密文转换为字符形式
cipher_text = [cipher_text char(bin2dec(reshape(num2str(cipher_text_bin), 8, [])'))];
end
end
% OFB模式解密
function [plain_text] = ofb_decrypt(cipher_text, key, iv)
% 设置初始向量
iv_bin = dec2bin(iv, 8);
iv_bin = reshape(iv_bin', 1, length(iv_bin(:)));
iv_bin = str2num(iv_bin(:))';
% 解密过程
plain_text = '';
for i = 1:length(cipher_text)
% 生成密钥流
if i == 1
key_stream_bin = des(iv_bin, key, 'encrypt');
else
key_stream_bin = des(key_stream_bin, key, 'encrypt');
end
% 解密
cipher_text_bin = dec2bin(cipher_text(i), 8);
cipher_text_bin = reshape(cipher_text_bin', 1, length(cipher_text_bin(:)));
cipher_text_bin = str2num(cipher_text_bin(:))';
plain_text_bin = bitxor(cipher_text_bin, key_stream_bin);
% 将明文转换为字符形式
plain_text = [plain_text char(bin2dec(reshape(num2str(plain_text_bin), 8, [])'))];
end
end
% 加密过程
plain_text = input('请输入需要加密的字符串:', 's');
cipher_text = ofb_encrypt(plain_text, key, iv);
disp(['加密后的字符串为:' cipher_text]);
% 解密过程
plain_text = ofb_decrypt(cipher_text, key, iv);
disp(['解密后的字符串为:' plain_text]);
```
运行结果如下:
```
请输入需要加密的字符串:Hello World!
加密后的字符串为:ÕáØûä¼?Q
解密后的字符串为:Hello World!
```