I am making a Caesar Library in C. The library source code contains the function below, which returns the encrypted equivalent of a given character:
char cypher_charac(char charac, int key)
{
if (islower(charac)) {
charac = 'a' + (charac - 'a' + key) % 26 ;
return charac ;
} else if (isupper(charac)) {
charac = 'A' + (charac - 'A' + key) % 26 ;
return charac
} else{
return charac ;
}
}
The function works great when called for encryption. However, when used for decryption (key = -key), the function returns non-alphabet characters.
I have checked multiple forums and different codes, but I just can't see it.
Thanks !
The problem is in how the %
remainder operation is defined for negative numbers in C - the remainder of a negative number is negative, and definitely not in the range 0 - 25! The definition of %
in C is different from that of Python, but similar to that of Javascript.
Consider the industry standard ROT13 algorithm, which uses 13 as the encryption key. Now if charac
= 'A'
, then charac - 'A' + key
will equal -13
and (-13) % 26
is still -13
. Add that to 'A'
and you will not have 'N'
but '4'
!
To get the correct decryption key, you must subtract the encryption key from 26, not negate it (i.e. key = 26 - key
). For ROT13, it will be 26 - 13
which again equals 13. For standard Caesarean ROT3, the decryption key will be 23. And for ROT26 the decryption key will be 0. Again, your approach would have worked in Python and perhaps many other programming languages, but that is because (-13) % 26
results in +13, not -13 there!