密码学算法——置换密码算法 c++实现

置换密码算法

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());
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值