c++ - c encrypt decrypt not working as expected -
i trying implement encode , decode of string based on page
http://www.thecrazyprogrammer.com/2016/11/caesar-cipher-c-c-encryption-decryption.html
and here code,
string encryptstring(string message){ int i, key=95828205; char ch; for(i = 0; message[i] != '\0'; ++i){ ch = message[i]; if(ch >= 'a' && ch <= 'z'){ ch = ch + key; if(ch > 'z'){ ch = ch - 'z' + 'a' - 1; } message[i] = ch; } else if(ch >= 'a' && ch <= 'z'){ ch = ch + key; if(ch > 'z'){ ch = ch - 'z' + 'a' - 1; } message[i] = ch; } } printf("encrypted message: %s", message); return message; } string decryptstring(string message){ int i, key=95828205; char ch; for(i = 0; message[i] != '\0'; ++i){ ch = message[i]; if(ch >= 'a' && ch <= 'z'){ ch = ch - key; if(ch < 'a'){ ch = ch + 'z' - 'a' + 1; } message[i] = ch; } else if(ch >= 'a' && ch <= 'z'){ ch = ch - key; if(ch < 'a'){ ch = ch + 'z' - 'a' + 1; } message[i] = ch; } } printf("decrypted message: %s", message); return message; }
and called function like,
string msg="test.com",msg1,msg2; msg1 = encryptstring(msg); msg2 = decryptstring(msg1);
but getting random character while decrypt data
you have defined
key=95828205;
then add character array , store array
if(ch >= 'a' && ch <= 'z'){ ch = ch + key; message[i] = ch; ...
and means character has overflowed , there random number.
then if try check (in encrypt)
if(ch >= 'a' && ch <= 'z'){ ch = ch - key;
there isn't high change value in interval.
to do
you should swap these lines (first real letter , compare it)
ch = ch - key; if(ch >= 'a' && ch <= 'z'){ ...
and use key
wont cause char
overflow (e.g. 5)
edit
test after changes
input
message: test key: 5
output encrypt
yjxy
output decrypt
test
Comments
Post a Comment