从 char 到 int 的加密

encryption from char to int

我正在用 C++ 编写一些加密程序,当我启动它时,控制台只打印一个字符,并且解密不起作用,当我进行加密/解密时,程序不会使用数字 nn 执行此操作,他用他的地址来做。对不起我的英语。

// Var
std::string text = "string";
const char *nn = text.c_str();

// Encryption
int x = (int(nn));
x = x * 3 - 100 * 2;
cout << "Numerical numbers: " << x << endl;
cout << "String: " << (char(x)) << endl;

// Decryption
x = (x - 100 * 2) / 3;
cout << "Numerical numbers: " << x << endl;
cout << "String: " << (char(x));

我想你想加密这个的每个字符:

std::string text = "string";

在这种情况下,您需要一个整数向量而不是单个 int 来存储每个编码字符:

std::vector<int> encrypted;

既然你知道向量的最终大小,你可以预先准备向量来分配必要的space,但这是可选的:

encrypted.reserve(text.size());

你必须一个一个地检查字符,对它们进行编码并将它们放入向量中:

for(auto &ch : text) {
    int x = ch * 3 - 100 * 2;
    encrypted.push_back(x);
}

生成的向量可以这样打印:

cout << "Numerical numbers: ";
for(auto x : encrypted) { cout << x << ", "; }
cout << endl;

解密类比:

std::string decrypted;
decrypted.reserve(encrypted.size());
for(auto &x : encrypted) {
    char ch = (x + 100 * 2) / 3;
    decrypted += ch;
}

除非你有限制,你必须使用公式 x * 3 - 100 * 2 for encryption/decryption,我建议你使用 XOR.

#include <iostream>
#include <string>

int main()
{
    // Var
    std::string text = "string", encrypt, decrypt;
    
    // Encryption
    for (int i = 0; i < text.length(); i++)
    {
        encrypt += text[i] ^ '1';
    }

    // Decryption
    for (int i = 0; i < encrypt.length(); i++)
    {
        decrypt += encrypt[i] ^ '1';
    }
    
    std::cout << "original text: " << text << std::endl << "encrypted text: " << encrypt << std::endl << "decrypted text: " << decrypt;
} 

以上代码的输出为:

original text: string

encrypted text: BECX_V

decrypted text: string

Here 是上述代码的一个工作示例。