How to use XOR to encrypt and decrypt a string in Kotlin

2 Answers

0 votes
fun xorEncryptDecrypt(input: String, key: Char): String {
    return input.map { it xor key }.joinToString("")
}

infix fun Char.xor(other: Char): Char {
    return this.code.xor(other.code).toChar()
}

fun main() {
    val originalText = "May the Force be with you."
    val key = 'K' // Encryption and decryption key

    // Encrypt the string
    val encryptedText = xorEncryptDecrypt(originalText, key)
    println("Encrypted: $encryptedText")

    // Decrypt the string (same function, same key)
    val decryptedText = xorEncryptDecrypt(encryptedText, key)
    println("Decrypted: $decryptedText")
}

 
  
/*
run:

Encrypted: *2k?#.k$9(.k).k<"?#k2$>e
Decrypted: May the Force be with you.

*/

 



answered Aug 17, 2025 by avibootz
0 votes
fun xorEncryptDecrypt(input: String, key: String): String {
    return input.mapIndexed { index, char ->
        char xor key[index % key.length]
    }.joinToString("")
}

infix fun Char.xor(other: Char): Char {
    return this.code.xor(other.code).toChar()
}

fun main() {
    val originalText = "May the Force be with you."
    val key = "Obelus" // String key for XOR operation

    // Encrypt the string
    val encryptedText = xorEncryptDecrypt(originalText, key)
    println("Encrypted: $encryptedText")

    // Decrypt the string (same function, same key)
    val decryptedText = xorEncryptDecrypt(encryptedText, key)
    println("Decrypted: $decryptedText")
}

 
  
/*
run:

Encrypted: L *B#  *B	U& L :L
Decrypted: May the Force be with you.

*/

 



answered Aug 17, 2025 by avibootz

Related questions

...