Reputation: 427
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.
Upvotes: 1
Views: 485
Reputation: 427
Okay, so I just noticed some instructions given by the author for decryption here at the end.
we can use the same function to decrypt, instead we’ll modify the shift value such that shift = 26-shift
So now decryption function looks like this:
fun decrypt(message:String,s:Int=3):String{
var decrpt:String = ""
for(m in message){
if(m.isLetter() && m.isUpperCase())
decrpt+=((m + (26-s) - 65).toInt() % 26 + 65).toChar()
else if(m.isLetter() && m.isLowerCase())
decrpt+=((m + (26-s) - 97).toInt() % 26 + 97).toChar()
else
decrpt+=m
}
return decrpt
}
Still, I am curious to know if I can use the same shift in the opposite direction to decrypt the encrypted text.
Upvotes: 1
Reputation: 311883
The handling of both the upper-case and lower-case decryption here is wrong. Subtracting s
is correct, but you need to also subtract 65 or 97 ('a' or 'A'), in order to be able to perform a modulu operation:
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
}
Upvotes: 0