密码学实践|C++实现维吉尼亚密码加解密

原理

我们用一个例子来理解:

加密:

明文:ILOVEYOU

密钥:VJJ

现在我们求密文

维吉尼亚的思想是需要我们将明文的字符与密钥的字符一一对齐,密钥长度不够则补齐

之后我们根据查表

I→V,由表可知对应的是D,那么第一个密文字符就是D

(此图片来自b站up主:

浪淘三千

之后我们按照上面的方法,以此类推,填完得到下面这张表就得到了密文:DUXQNEES

(我们通过代码实现的时候只用求出明文的字符+对应密钥的字符%26即可得到对应的密文)

解密:

(密文的字符-密钥的字符+26)%26,求出所有明文(+26是因为防止出现负数)

代码

此代码只简单实现了明文输入情况全为大写字母的情况

#include <iostream>
#include <string>
using namespace std;
//密钥k 明文p 密文c 
//加密函数
string vigenereEncrypt(const string& p,const string&k){
	string c;
	for(int i;i<p.length();i++){
		char pchar=p[i];
		char kchar=k[i%k.length()];
		char cchar=(pchar+kchar)%26+'A';
		c+=cchar;
	}
	return c;
 } 
// 解密函数
 string vigenereDecrypt(const string& encrypt, const string& k) {
    string pa;
    for (int i = 0; i <encrypt.length(); i++) {
        char encryptchar =encrypt[i];
        char kchar = k[i % k.length()];
        char pachar = (encryptchar - kchar+26) % 26 + 'A';
        pa += pachar;
    }
    return pa;
}
 int main(){
 	string p;
 	cin>>p;
 	string k;
 	cin>>k;
 	string encrypt=vigenereEncrypt(p,k);
 	string decrypt=vigenereDecrypt(encrypt,k);
 	cout<<"密文是:"<<encrypt<<endl;
 	cout<<"明文是:"<<decrypt<<endl;
 }

输出

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,维密码是一种多表密码,通过多个凯撒密码表的组合来提高密强度。下面是用C++实现密码解密的示例代码: ```c++ #include <iostream> #include <string> using namespace std; string encrypt(string plaintext, string key) { string ciphertext = ""; int keyIndex = 0; for (int i = 0; i < plaintext.length(); i++) { char c = plaintext[i]; if (isalpha(c)) { int keyChar = key[keyIndex] - 'a'; int shift = tolower(c) - 'a' + keyChar; c = (shift % 26) + 'a'; keyIndex = (keyIndex + 1) % key.length(); } ciphertext += c; } return ciphertext; } string decrypt(string ciphertext, string key) { string plaintext = ""; int keyIndex = 0; for (int i = 0; i < ciphertext.length(); i++) { char c = ciphertext[i]; if (isalpha(c)) { int keyChar = key[keyIndex] - 'a'; int shift = tolower(c) - 'a' - keyChar; if (shift < 0) shift += 26; c = shift + 'a'; keyIndex = (keyIndex + 1) % key.length(); } plaintext += c; } return plaintext; } int main() { string plaintext = "This is a secret message."; string key = "secret"; string ciphertext = encrypt(plaintext, key); cout << "Ciphertext: " << ciphertext << endl; string decryptedText = decrypt(ciphertext, key); cout << "Decrypted text: " << decryptedText << endl; return 0; } ``` 在这个示例代码中,我们定义了两个函数`encrypt()`和`decrypt()`,分别用于密和解密。这两个函数都接受两个字符串参数,分别是明文/密文和密钥。在密和解密过程中,我们都需要遍历明文/密文中的每个字符,并根据密钥中的字符来计算移位量,从而实现密和解密的过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值