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

2 Answers

0 votes
object XOREncryption {
  def xorEncryptDecrypt(input: String, key: Char): String = {
    input.map(char => (char ^ key).toChar)
  }

  def main(args: Array[String]): Unit = {
    val originalText = "May the Force be with you."
    val key = 'K' // Key for XOR operation

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

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


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

 



answered Aug 17, 2025 by avibootz
0 votes
object XOREncryption {
  def xorEncryptDecrypt(input: String, key: String): String = {
    input.zipWithIndex.map { case (char, i) =>
      val keyChar = key(i % key.length)
      (char ^ keyChar).toChar
    }.mkString
  }

  def main(args: Array[String]): Unit = {
    val originalText = "May the Force be with you."
    val key = "Obelus" // String key for XOR operation

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

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



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

 



answered Aug 17, 2025 by avibootz

Related questions

...