Código: Seleccionar todo
import Codec.Binary.UTF8.Light(toBits,fromBits)
import Data.List(elemIndices,tails)
import Data.List.Split (splitOn)
import Data.Char(chr,ord)
data Option = Encrypt | Decrypt
base64 :: String -> Option -> String
base64 xs ys = case ys of
Encrypt -> cifrar xs
Decrypt -> descifrar (concat$splitOn "=" xs)
where
cONST = [chr x|x<-[0x41..0x5A]++[0x61..0x7A]++[0x30..0x39]++[0x2B,0x2F]]
cifrar :: String -> String
cifrar [] = []
cifrar xs
|length xs == 0x01 = map(cONST!!)[var8,var9]++"=="
|length xs == 0x02 = map(cONST !!)[var5,var6,var7]++"="
|otherwise = map(cONST !!)[var,var2,var3,var4]++cifrar (drop 0x03 xs)
where
var=fromIntegral.fromBits.take 0x06.concat$[toBits.fromIntegral.ord$z | z <- take 0x03 xs]
var2=fromIntegral.fromBits.take 0x06.drop 0x06.concat$[toBits.fromIntegral.ord$z | z <- take 0x03 xs]
var3=fromIntegral.fromBits.take 0x06.drop 0x0C.concat$[toBits.fromIntegral.ord$z | z <- take 0x03 xs]
var4=fromIntegral.fromBits.take 0x06.drop 0x12.concat$[toBits.fromIntegral.ord$z | z <- take 0x03 xs]
var5=fromIntegral.fromBits.take 0x06.concat$[toBits.fromIntegral.ord$z | z <- xs]
var6=fromIntegral.fromBits.take 0x06.drop 0x06.concat$[toBits.fromIntegral.ord$z | z <- xs]
var7=fromIntegral.fromBits.take 0x06.drop 0x0C$concat([toBits.fromIntegral.ord$z | z <- xs])++[0x0,0x0]
var8=fromIntegral.fromBits.take 0x06.concat$[toBits.fromIntegral.ord$z | z <- xs]
var9=fromIntegral.fromBits.take 0x06.drop 0x06$concat([toBits.fromIntegral.ord$z | z <- xs])++[0x0,0x0,0x0,0x0]
descifrar :: String -> String
descifrar [] = []
descifrar xs
|length xs == 0x02 = [me6]
|length xs == 0x03 = [me4,me5]
|otherwise = [me,me2,me3]++descifrar (drop 0x04 xs)
where
me=chr.fromIntegral.fromBits.take 0x08.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- take 0x04 xs]
me2=chr.fromIntegral.fromBits.take 0x08.drop 0x08.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- take 0x04 xs]
me3=chr.fromIntegral.fromBits.take 0x08.drop 0x10.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- take 0x04 xs]
me4=chr.fromIntegral.fromBits.take 0x08.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- xs]
me5=chr.fromIntegral.fromBits.take 0x08.drop 0x08.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- xs]
me6=chr.fromIntegral.fromBits.take 0x08.concat$[tails(toBits(fromIntegral((elemIndices x cONST) !! 0x0))) !! 0x02 | x <- xs]
Muestra:
Código: Seleccionar todo
*Main> base64 "pim pam toma lacasitos" Encrypt
"cGltIHBhbSB0b21hIGxhY2FzaXRvcw=="
*Main> base64 "cGltIHBhbSB0b21hIGxhY2FzaXRvcw==" Decrypt
"pim pam toma lacasitos"
*Main>