加密四个字符为后四位c++
时间: 2024-10-11 21:08:03 浏览: 24
加密四个字符通常是指将明文转换成密文的过程,在C++中,我们可以使用简单的替换密码或者更复杂的算法,如凯撒密码、MD5哈希等。这里我将演示一个基于字母表替换的简单示例,比如Caesar Cipher(凯撒密码),偏移量为3:
```cpp
#include <iostream>
#include <string>
// 凯撒密码加密函数,输入4个字符,偏移量为3
std::string caesar_encrypt(std::string input, int shift) {
std::string encrypted = "";
for (char c : input) {
if (isalpha(c)) { // 检查是否为英文字母
char shifted = static_cast<char>((c + shift - 'a') % 26 + 'a'); // 遵循循环性质
if (isupper(c))
shifted = static_cast<char>((shifted - 'A' + 26) % 26 + 'A');
encrypted += shifted;
} else {
encrypted += c; // 非字母字符直接保留
}
}
return encrypted;
}
int main() {
std::string unencrypted = "hello"; // 示例原始字符串
std::string encrypted_text = caesar_encrypt(unencrypted.substr(-4), 3); // 取最后四位字符并加密
std::cout << "Original (last 4 chars): " << unencrypted.substr(-4) << "\n";
std::cout << "Encrypted: " << encrypted_text << "\n";
阅读全文