I have a question to implement an encryption code. Follow the code below:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string criptografar(string mensagem);
string descriptografar(string mensagem);
string mens_original;
string mens_criptografada;
string mens_descriptografada;
mens_original = "A";
cout<< "Mensagem original: "<< mens_original << endl;
mens_criptografada = criptografar(mens_original);
cout << "Mensagem criptografada: " << mens_criptografada << endl;
mens_descriptografada = descriptografar(mens_criptografada);
cout << "Mensagem descriptografada: " << mens_descriptografada << endl;
return 0;
}
string criptografar(string mensagem)
{
int tamanho = 0;
tamanho = mensagem.length();
for (int i = 0 ; i < tamanho; i++)
{
mensagem[i] = (int) mensagem[i] * 2 ;
}
return mensagem;
}
string descriptografar(string mensagem)
{
int tamanho = 0;
tamanho = mensagem.length();
for (int i = 0 ; i < tamanho ; i++)
{
mensagem[i] = (int) mensagem [i] / 2;
}
return mensagem;
}
Well, when we put the following:
mensagem[i] = (int) mensagem[i] + 2 //criptografar;
mensagem[i] = (int) mensagem[i] - 2 // descriptografar;
The program runs, calculates and returns the new value (encryption) of the letter "A", which in the case goes to "Ç", and at the time of decrypting the value returns to "A". >
If we do:
mensagem[i] = (int) mensagem[i] * 2 //criptografar;
mensagem[i] = (int) mensagem[i] / 2 // descriptografar;
The value of "A" goes to "is" normal (2 * 65 = 130 -> value of "is") but in the decrypt up to 1 moment before the FOR loop of the function decrypts the value of 'message' = 'is' which is what we want, but when entering into the loop the value takes on another value (negative) and ends up resulting in another character of the ASCII table, and checking the value of 'message [i]' = (negative value). of course why if message [i] took a negative value any result, in the end it would have to be negative. My question is: Why is this happening? If you have solutions please help me! NOTE: I have already checked the ASCII table values to see if you were extrapolating when multiplying, but that is not the case.