I can not seem to figure out why only certain letters in my decryption are not working. I am trying to decrypt the letters kddkmu with a key of 10. It is suppose to come out to attack but every time I run the code it comes out to aZZack. I believe the problem has something to do with my modulus operation but no matter what I do I cant figure out the problem.
int key = 10;
ciphertext = "kddkmu";
plaintext = shift_decrypt(ciphertext, key);
cout << "2. Decryption of the ciphertext: " << ciphertext << endl;
cout << " Key: " << key << endl;
cout << " Plaintext; " << plaintext << endl << endl;
with
string shift_decrypt(string p, int a)
{
string dtext = "";
for (int i = 0; i < p.length(); i++)
{
dtext += char(int(p[i] - a - 97) % 26 + 97);
}
return dtext;
}
I am not getting any errors its just decrypting the dd as ZZ for some odd reason
I don't suggest subtraction with modulus (remainder) operator.
We know that (X * 26) % 26 == 0
for all X.
So, we can add an extra 26 with no cost. To subtract, we can add (26 - Y) to the value and still have a positive value.
Step by step:
1) Shift the character into the range of 0 - 25
, inclusive:
int value = letter - 'a';
2) Remove the Caesar offset by "subtracting" the key:
value = (value + 26 - key) % 26;
3) Shift the value to the range a
to z
:
char decrypted_letter = value + 'a';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.