0

I'm currently working on a Vigenère Encoder/Decoder in Kotlin. I already did it in Python and the encoding works fine, but I have problems with the decoding in Kotlin.

Python implementation of the decoding:

def decode(data: str):
    key = "SecureKey"
    decoded_message = ""
    i = 0

    for char in data:
        if char.isalpha():
            if char.isupper():
                decoded_message += chr(((ord(char) - ord(key.upper()[i % len(key)])) % 26 + 65))
            else:
                decoded_message += chr(((ord(char) - ord(key.lower()[i % len(key)])) % 26 + 97))
            i += 1
        else:
            decoded_message += char
    
    return decoded_message

Kotlin implementation:

fun decodeVigenere(message: String): String {
    val key = "SecureKey"
    var decodedMessage: StringBuilder = StringBuilder()
    var i = 0
    for (char in message) {
        if (char.isLetter()) {
            if (char.isUpperCase()) {
                decodedMessage.append(((char.code - key.uppercase()[i % key.length].code) % 26 + 65).toChar())
            } else {
                decodedMessage.append(((char.code - key.lowercase()[i % key.length].code) % 26 + 97).toChar())
            }
            i += 1
        } else {
            decodedMessage.append(char)
        }
    }
    return decodedMessage.toString()
}

As you can see, it should be the same operations, just in Kotlin. The Python version works, I compared it to CyberChef and got the same results. For some reason the Kotlin version doesn't return the correct decoded message.

I also copied the encoding from Python and I didn't have problems with Kotlin.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Liam K.
  • 75
  • 7
  • 1
    What does it return instead? – mkrieger1 Nov 01 '22 at 22:45
  • 1
    This behavior is because `%` works differently in Python and Kotlin. As mentioned in the answers of the linked question, using `.mod(26)` instead of `% 26` will behave like Python (returning a positive value) and your decoding will work as expected. – shriakhilc Nov 01 '22 at 23:11

0 Answers0