Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.util.Random
- object Vinger {
- def main(args: Array[String]) {
- println(Cipher.encrypt("TO JEST BARDZO TAJNY TEKST"))
- }
- object Cipher {
- val EMPTY = "";
- val LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- private def encryptWithFullKey(text: String, key: String): String =
- if(key.length < text.length) throw new Error("Key is too short") else{
- def encryptAcc(acc: String): String = if (acc.length() < text.length()) {
- val offset = acc.length
- if (LETTERS contains (text(offset))) {
- val keyOffset = LETTERS indexOf key(offset)
- val letterOffset = LETTERS indexOf text(offset)
- val finalOffset = (letterOffset + keyOffset) % LETTERS.size
- encryptAcc(acc + LETTERS(finalOffset))
- } else encryptAcc(acc + text(offset))
- } else acc;
- encryptAcc(EMPTY)
- }
- def encrypt(text: String, key: String): String = if(key.length < text.length) {
- var finalKey = key;
- val times = (text.length.toDouble / key.length).toInt + 1
- for(a <- 0 to times) {finalKey = finalKey + key}
- encryptWithFullKey(text, finalKey.substring(0, text.length))
- }else encryptWithFullKey(text, key)
- def encrypt(text: String): (String, String) = {
- val key = text.map(_ => LETTERS.charAt(Random.nextInt(LETTERS.length)))
- return (encryptWithFullKey(text, key), key)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement