Base64 Encoding in Haskell
Here’s the translation of the Base64 Encoding example from Go to Haskell, formatted in Markdown suitable for Hugo:
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as C8
main :: IO ()
main = do
-- Here's the string we'll encode/decode.
let data = "abc123!?$*&()'-=@~"
-- Haskell provides base64 encoding/decoding through the base64-bytestring package.
-- Here's how to encode using the standard encoder.
let sEnc = B64.encode $ C8.pack data
putStrLn $ C8.unpack sEnc
-- Decoding may return an error, which you can handle with Either.
case B64.decode sEnc of
Left err -> putStrLn $ "Decoding error: " ++ err
Right sDec -> putStrLn $ C8.unpack sDec
putStrLn ""
-- This encodes/decodes using a URL-compatible base64 format.
let uEnc = B64.encodeUrlSafe $ C8.pack data
putStrLn $ C8.unpack uEnc
case B64.decodeUrlSafe uEnc of
Left err -> putStrLn $ "Decoding error: " ++ err
Right uDec -> putStrLn $ C8.unpack uDec
Haskell provides support for base64 encoding/decoding through the base64-bytestring
package. This example demonstrates how to use it.
First, we import the necessary modules: Data.ByteString.Base64
for base64 operations and Data.ByteString.Char8
for working with ByteStrings.
In the main
function, we define our sample string data
.
For standard base64 encoding:
- We use
B64.encode
to encode the ByteString version of our data. - We print the encoded string after converting it back to a regular String.
For decoding:
- We use
B64.decode
which returns anEither
type. - We handle both success and error cases using pattern matching.
The process is similar for URL-safe base64 encoding/decoding, but we use B64.encodeUrlSafe
and B64.decodeUrlSafe
instead.
Note that in Haskell, we’re working with ByteStrings instead of the []byte
type used in the original example. This is idiomatic for Haskell when dealing with binary data or text that needs to be processed efficiently.
To run this program:
$ runhaskell base64_encoding.hs
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.