Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.40 KB | None | 0 0
  1. import scala.util.Random
  2.  
  3. object Vinger {
  4.   def main(args: Array[String]) {
  5.     println(Cipher.encrypt("TO JEST BARDZO TAJNY TEKST"))
  6.   }
  7.   object Cipher {
  8.     val EMPTY = "";
  9.     val LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10.     private def encryptWithFullKey(text: String, key: String): String =
  11.       if(key.length < text.length) throw new Error("Key is too short") else{
  12.       def encryptAcc(acc: String): String = if (acc.length() < text.length()) {
  13.         val offset = acc.length
  14.         if (LETTERS contains (text(offset))) {
  15.           val keyOffset = LETTERS indexOf key(offset)
  16.           val letterOffset = LETTERS indexOf text(offset)
  17.           val finalOffset = (letterOffset + keyOffset) % LETTERS.size
  18.           encryptAcc(acc + LETTERS(finalOffset))
  19.         } else encryptAcc(acc + text(offset))
  20.       } else acc;
  21.       encryptAcc(EMPTY)
  22.     }
  23.    
  24.     def encrypt(text: String, key: String): String = if(key.length < text.length) {
  25.       var finalKey = key;
  26.       val times = (text.length.toDouble / key.length).toInt + 1
  27.       for(a <- 0 to times) {finalKey = finalKey + key}
  28.       encryptWithFullKey(text, finalKey.substring(0, text.length))
  29.     }else encryptWithFullKey(text, key)
  30.    
  31.     def encrypt(text: String): (String, String) = {
  32.       val key = text.map(_ => LETTERS.charAt(Random.nextInt(LETTERS.length)))
  33.       return (encryptWithFullKey(text, key), key)
  34.     }
  35.    
  36.   }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement