置换密码算法
1.算法原理
置换密码算法的原理是不改变明文字符,只将字符在明文中的排列顺序改变,从而实现明文信息的加密。
2.结果展示
能够实现密钥长度为1~9的周期置换
3.具体过程
3.1图形化界面
本过程采用VS自带的MFC,实现较为简单,如果有问题,可以查看MFC简要使用说明
3.2密钥生成函数
void CMFCApplication1Dlg::OnBnClickedButton1(){
TCHAR szText[100] = { 0 };
m_combo.GetLBText(m_combo.GetCurSel(), szText);
int key = _tstof(szText);
ord = key;
int cnt = 0;
while (cnt!=key) {
int k_word = rand() % key + 1;
if (change[k_word] == 0) {
cnt++;
jiami[cnt] = k_word;
jiemi[k_word] = cnt;
change[k_word] = 1;
a = char(k_word + '0');
if (cnt == 1) GetDlgItem(IDC_EDIT1)->SetWindowText(a.c_str());
else if (cnt == 2) GetDlgItem(IDC_EDIT2)->SetWindowText(a.c_str());
else if (cnt == 3) GetDlgItem(IDC_EDIT3)->SetWindowText(a.c_str());
else if (cnt == 4) GetDlgItem(IDC_EDIT4)->SetWindowText(a.c_str());
else if (cnt == 5) GetDlgItem(IDC_EDIT5)->SetWindowText(a.c_str());
else if (cnt == 6) GetDlgItem(IDC_EDIT6)->SetWindowText(a.c_str());
else if (cnt == 7) GetDlgItem(IDC_EDIT7)->SetWindowText(a.c_str());
else if (cnt == 8) GetDlgItem(IDC_EDIT8)->SetWindowText(a.c_str());
else if (cnt == 9) GetDlgItem(IDC_EDIT9)->SetWindowText(a.c_str());
}
}
}
本段代码对应图形界面的“生成密钥”按钮,选择密钥长对应后,会随机生成对应长度的密钥,并将加密变换记录到数组jiami中,将解密变换记录到数组jiemi中,并将密钥显示到对应位置。
3.3加密函数
void CMFCApplication1Dlg::OnBnClickedButton2(){
GetDlgItem(IDC_EDIT11)->SetWindowText("");
CString plaintext_temp;
GetDlgItem(IDC_EDIT10)->GetWindowText(plaintext_temp);
string plaintext = (LPCSTR)(CString)(plaintext_temp);
string ciphertext = "";
if (plaintext.length() % ord == 0) {
for (int i = 0; i < (plaintext.length()/ord); i++) {
for (int j = 1; j <= ord; j++) {
ciphertext += plaintext[jiami[j]+ord*i-1];
}
}
}
else {
MessageBox("输入不符合规定,请重新输入明文");
GetDlgItem(IDC_EDIT10)->SetWindowText("");
ciphertext = "";
}
GetDlgItem(IDC_EDIT11)->SetWindowText(ciphertext.c_str());
}
3.4解密函数
void CMFCApplication1Dlg::OnBnClickedButton3(){
GetDlgItem(IDC_EDIT10)->SetWindowText("");
CString ciphertext_temp;
GetDlgItem(IDC_EDIT11)->GetWindowText(ciphertext_temp);
string ciphertext = (LPCSTR)(CString)(ciphertext_temp);
string plaintext = "";
if (ciphertext.length() % ord == 0) {
for (int i = 0; i < (ciphertext.length() / ord); i++) {
for (int j = 1; j <= ord; j++) {
plaintext += ciphertext[jiemi[j] + ord * i - 1];
}
}
}
else {
MessageBox("输入不符合规定,请重新输入密文");
GetDlgItem(IDC_EDIT11)->SetWindowText("");
plaintext = "";
}
GetDlgItem(IDC_EDIT10)->SetWindowText(plaintext.c_str());
}