I am trying to implement Caesar Cipher in Kotlin. In Caesar Cipher you encrypt the message by substituting a letter with some fixed number of positions down the alphabet. You can look here for more information and also the approach I adopted for encryption and decryption.
My encryption works properly.
Note: s is for a shift in alphabets and I have kept it as 3 by default.
fun encrypt(message:String,s:Int=3):String{
var encrpt:String = ""
for(m in message){
if(m.isLetter() && m.isUpperCase())
encrpt+=((m + s - 65).toInt() % 26 + 65).toChar()
else if(m.isLetter() && m.isLowerCase())
encrpt+=((m + s - 97).toInt() % 26 + 97).toChar()
else
encrpt+=m
}
return encrpt
}
For decryption instead of adding 3, I am subtracting 3. But I am facing some problem in decryption and that too only for lower case letters.
This is my code for decryption:
fun decrypt(message:String,s:Int=3):String{
var decrpt:String = ""
for(m in message){
if(m.isLetter() && m.isUpperCase())
decrpt+=((m - s + 65).toInt() % 26 + 65).toChar()
else if(m.isLetter() && m.isLowerCase())
decrpt+=((m - s + 97).toInt() % 26 + 97).toChar()
else
decrpt+=m
}
return decrpt
}
For uppercase letters my output is fine:
J->G
But for lowercase letters, the output is incorrect.
j->s
I have used this image for the decimal values of characters. Thank you for looking into my problem.