使用C++实现Vigenere密码的加密
时间: 2024-04-10 18:27:12 浏览: 11
当然可以!下面是一个使用C++实现Vigenere密码的加密的示例代码:
```cpp
#include <iostream>
#include <string>
std::string encryptVigenere(const std::string& plainText, const std::string& key) {
std::string encryptedText = plainText;
int keyLength = key.length();
int textLength = plainText.length();
for (int i = 0; i < textLength; i++) {
char plainChar = plainText[i];
char keyChar = key[i % keyLength];
char encryptedChar;
if (isalpha(plainChar)) {
if (islower(plainChar)) {
encryptedChar = 'a' + (plainChar - 'a' + toupper(keyChar) - 'A') % 26;
} else {
encryptedChar = 'A' + (plainChar - 'A' + toupper(keyChar) - 'A') % 26;
}
} else {
encryptedChar = plainChar;
}
encryptedText[i] = encryptedChar;
}
return encryptedText;
}
int main() {
std::string plainText, key;
std::cout << "Enter the plain text: ";
std::getline(std::cin, plainText);
std::cout << "Enter the key: ";
std::getline(std::cin, key);
std::string encryptedText = encryptVigenere(plainText, key);
std::cout << "Encrypted text: " << encryptedText << std::endl;
return 0;
}
```
这个示例代码中的 `encryptVigenere` 函数接受两个参数:明文和密钥。它会对明文进行 Vigenere 加密,并返回加密后的密文。
在 `main` 函数中,用户可以输入明文和密钥,然后调用 `encryptVigenere` 函数进行加密,并输出加密后的密文。
请注意,这只是一个简单的实现示例,没有包含对输入的合法性进行检查。在实际应用中,你可能需要添加更多的错误处理和边界情况的处理。