c encrypt decrypt not working as expected

Home / Uncategorized / c encrypt decrypt not working as expected

Question:
I am trying to implement encode and decode of string based on this page

Caesar Cipher in C and C++ [Encryption & Decryption]

And here is the code,
string encryptString(string message){

int i, key=95828205;
char ch;
for(i = 0; message[i] != ‘’; ++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] != ‘’; ++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 the function like, string msg="test.com",msg1,msg2; msg1 = encryptString(msg); msg2 = decryptString(msg1); But I am getting some random character while decrypt the data back


Answer:
You have defined
key=95828205;
Then you add it to character from an array and store it to array
if(ch >= ‘a’ && ch <= 'z'){ ch = ch + key; message[i] = ch; ... And it means that character has overflowed and there is some random number. Then if you try to check (in encrypt) if(ch >= ‘a’ && ch <= 'z'){ ch = ch - key; There isn't high change that the value will be in that interval. TO DO You should swap these lines (first get real letter and then compare it) ch = ch - key; if(ch >= ‘a’ && ch <= 'z'){ ... And use key which wont cause char overflow (e.g. 5) EDIT Test after changes Input Message: test Key: 5 Output from encrypt yjxy Output from decrypt test Read more

Leave a Reply

Your email address will not be published. Required fields are marked *