Guest User

Untitled

a guest
Dec 19th, 2014
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. val message:String = "Hello World!"
  2. val key:String = "Key"
  3.  
  4. val encrypted = Cipher(message).simpleOffset(5)
  5. println(encrypted) "Mjqqt%twqi&"
  6. val decrypted = Cipher(encrypted).simpleOffset(-5)
  7. println(decrypted) "Hello World!"
  8.  
  9. val encrypted2 = Cipher(message).encryptWith(key)
  10. println(encrypted2) "5l?Yv;Dv?Yk<"
  11. val decrypted2 = Cipher(encrypted2).decryptWith(key)
  12. println(decrypted2) "Hello World!"
  13.  
  14. class Cipher(message:String) {
  15. val cHARMIN = 32 //Lower bound
  16. val cHARMAX = 126 //Upper bound
  17.  
  18. //"Wraps" a character, so it doesn't go under cHARMIN, or over cHARMAX
  19. //Takes an Int so the Char can't underflow prior to being passed in
  20. private def wrap(n:Int):Char =
  21. if (n > cHARMAX) (n - cHARMAX + cHARMIN).toChar
  22. else if (n < cHARMIN) (n - cHARMIN + cHARMAX).toChar
  23. else n.toChar
  24.  
  25. private def forString[A](str:String)(f:Char => Char):String = {
  26. var newStr = ""
  27. for(c <- str) { newStr += f(c) }
  28. newStr
  29. }
  30.  
  31. //Creates a repeated key that's at least as long as the message to be encrypted
  32. private def getRepKey(key:String):String =
  33. if (key.length >= message.length) key
  34. else key * (message.length / key.length + 1)
  35.  
  36. //Modifies a letter in the message, based on the respective letter in the key,
  37. // and the given binary operator
  38. private def modifyWithStringWith(f:(Int,Int) => Int)(strKey:String):String = {
  39. var newString = ""
  40. (message zip getRepKey(strKey)).foreach { case (c1,c2) =>
  41. newString += wrap( f(c1,c2) ) }
  42. newString
  43. }
  44.  
  45. //Offsets each character in a String by a given offset
  46. def simpleOffset(offset:Int):String =
  47. forString(message) { (c:Char) =>
  48. val newChar = (c + offset).toChar
  49. wrap((c + offset).toChar)
  50. }
  51.  
  52. //Encrypts/Decrypts using another String as the key
  53. def encryptWith(key:String):String =
  54. modifyWithStringWith(_+_)(key)
  55.  
  56. def decryptWith(key:String):String =
  57. modifyWithStringWith(_-_)(key)
  58. }
  59.  
  60. object Cipher {
  61. def apply(msg:String):Cipher = new Cipher(msg)
  62. }
Add Comment
Please, Sign In to add comment