How to resolve the algorithm Vigenère cipher step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Vigenère cipher step by step in the Scala programming language

Table of Contents

Problem Statement

Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Vigenère cipher step by step in the Scala programming language

Source code in the scala programming language

object Vigenere {
  def encrypt(msg: String, key: String) : String = {
    var result: String = ""
    var j = 0

    for (i <- 0 to msg.length - 1) {
      val c = msg.charAt(i)
      if (c >= 'A' && c <= 'Z') {
        result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar
        j = (j + 1) % key.length
      }
    }

    return result
  }

  def decrypt(msg: String, key: String) : String = {
    var result: String = ""
    var j = 0

    for (i <- 0 to msg.length - 1) {
      val c = msg.charAt(i)
      if (c >= 'A' && c <= 'Z') {
        result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar
        j = (j + 1) % key.length
      }
    }

    return result
  }
}

println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))


  

You may also check:How to resolve the algorithm Sequence of primorial primes step by step in the Factor programming language
You may also check:How to resolve the algorithm Middle three digits step by step in the jq programming language
You may also check:How to resolve the algorithm Knuth shuffle step by step in the zkl programming language
You may also check:How to resolve the algorithm Guess the number step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Find the intersection of a line with a plane step by step in the Factor programming language