2
I have a question about implementing 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, makes the calculations and returns the new value (encryption) of the letter "A", which in this case goes to "Ç", and at the time of decrypting the value returns to "A".
If we ever 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 at the time of decrypt until 1 moment before the FOR loop of the decryption function the value of 'message' = "is" which is what we want, but when entering the loop the value assumes another value (negative) and ends up resulting in another character of the ASCII table, and by checking the value of 'message[i]' = (negative value). of course why if message[i] assumed a negative value whatever the 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 already checked the values of the ASCII table to see if it was extrapolating when doing the multiplication, but not the case.