blob: 28655c1d7b18f297e40ea75678a54d8d1d464e48 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
--
-- Miguel's Naive Base64 Encoder
--
-- Coded on a winter afterfnoon on 19th Feb 2018 A.D.
-- to fully understand base64 encoding and play with
-- haskell, which is always an indisputable pleasure.
--
-- The following lines were written in full awareness
-- that 'libraries' for this purpose, which perform way
-- better, are in existence.
--
-- Coded in big anger due to nick's stories about saving his binary
-- format, encrypted passwords in an ascii config file, featuring
-- strange letters and characters.
--
-- Example Usage: echo "just testing" | stack runghc base64.hs | stack runghc base64 -- -d
-- (You can cross check with base64 / base64 -d)
import System.Environment
import qualified Data.List.Split as T
import qualified Data.List as L
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Lazy as B
--import Data.ByteString.Char8 as C
import Text.Printf
import Data.Maybe
import Data.Char
import Control.Monad
main = do args<-getArgs
-- if Prelude.length args == 0 then go encode64
-- else when (args!!0 == "-d") $ go decode64
go encode64
where go f = B.getContents >>= B.putStr.B.pack.f.B.unpack
fromBase64 x = (['A'..'Z']++['a'..'z']++['0'..'9']++['+','/']) !! x
--mapBase64 = M.fromList $ C.map (\x-> (fromBase64 x,x)) [0..63]
--binToDec = sum . C.map (2^) . L.findIndices (=='1') . C.reverse
encode64 x = L.map (printf "%08b") xi
where xi=map fromIntegral x :: [Int]
--x++repeat (fromIntegral $ ord '=')
{-
encode64 x = pad64 (C.length x) . C.map (fromBase64 . binToDec) . T.chunksOf 6 .
C.concat . C.map (printf "%08b" ) $ x ++ cycle 0
-}
{-
decode64 x = C.map (chr . binToDec) . T.chunksOf 8 .
C.concat . C.map ( printf "%06b" . fromJust) . C.filter isJust .
C.map (flip M.lookup mapBase64) $ x
-}
{-
pad64 l = (++(C.take m ((cycle "=")))) . C.take ((l+m)*3 `div` 2 -3-m)
where m = mod (3 - mod l 3) 3
-}
|