Created
July 6, 2014 01:29
-
-
Save phillipjohnson/819040ea0a1ad2fa1d1e to your computer and use it in GitHub Desktop.
Scala base64 encryption with alternative encodings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val b64_ZH = "的一是不了人我在有他这中大来上国个到说们为子和你地出道也时年得" + | |
"就那要下以生会自着去之过家学对可她里后小么心多天而能好都然没日。" | |
val b64_EN = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
val input = "Man is distinguished, not only by his reason, but by this singular " + | |
"passion from other animals, which is a lust of the mind, that by a " + | |
"perseverance of delight in the continued and indefatigable generation " + | |
"of knowledge, exceeds the short vehemence of any carnal pleasure." | |
def strToAscii(s: String) : List[Int] = { | |
val ascii = for { | |
c <- s | |
} yield c.toInt | |
ascii.toList | |
} | |
def asciiToBinary(ascii: List[Int]) = { | |
val binaryList = for { | |
n <- ascii | |
} yield ("%8s" format (Integer.toBinaryString(n))).replace(' ','0') | |
binaryList.reduceLeft((a,b) => a + b) | |
} | |
def binaryToNumbers(binary: String) : List[Int] = { | |
def peel(s: String, acc: List[Int]) : List[Int] = { | |
if(s.length >= 6) { | |
peel(s drop 6, acc :+ Integer.parseInt(s take 6,2)) | |
} else if(s=="") { | |
acc | |
} else { | |
//Pad the string to get a six-character string | |
acc :+ Integer.parseInt(s + ("0" * (6 - s.length)),2) | |
} | |
} | |
peel(binary,List()) | |
} | |
def numbersToB64(nums: List[Int], b64map: String) : String = { | |
(nums map (n => b64map(n))).mkString | |
} | |
val t = strToAscii(input) | |
val bin = asciiToBinary(t) | |
val nums = binaryToNumbers(bin) | |
println(numbersToB64(nums,b64_ZH)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment