based/src/Encoding/Base64.hs

71 lines
2.3 KiB
Haskell

module Encoding.Base64
( enc64
, dec64
, enc64url
, dec64url
) where
import Data.ByteString.UTF8 as BSU -- from utf8-string
import Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Codec.Binary.Base64 as B64
import qualified Data.ByteString.Base64 as B64L
import qualified Codec.Binary.Base64Url as B64U
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
-- encodeToBase64 :: C.ByteString -> Either String C.ByteString
-- encodeToBase64 bs =
-- case B64.encode bs of
-- encoded | C.null encoded -> Left "Failed to encode Base64.\n"
-- | otherwise -> Right encoded
-- decodeFromBase64 :: C.ByteString -> Either String C.ByteString
-- decodeFromBase64 bs =
-- case B64L.decodeLenient bs of
-- decoded | C.null decoded -> Left "Failed to decode from Base64.\n"
-- | otherwise -> Right decoded
-- | otherwise -> Right (BSU.toString decoded)
-- Left err -> Left $ "Failed to decode from base64: " ++ err
-- Right decoded -> Right decoded
-- dec64 :: String -> String
-- dec64 input =
-- case decodeFromBase64 (BSU.fromString input) of
-- Right byteString -> T.unpack (T.decodeUtf8 byteString)
-- Left errMsg -> "Error: " ++ errMsg
-- enc64 :: String -> String
-- enc64 input =
-- case encodeToBase64 (BSU.fromString input) of
-- Right byteString -> C.unpack byteString
-- Left errMsg -> "Error: " ++ errMsg
dec64 :: B.ByteString -> B.ByteString
dec64 input = case B64.decode input of
Right byteString -> byteString
Left _ -> BC.pack "Error: Invalid Base64 input"
enc64 :: B.ByteString -> B.ByteString
enc64 = B64.encode
-- dec64url :: String -> String
-- dec64url input =
-- case B64.decode (BSU.fromString input) of
-- Right decoded -> T.unpack (T.decodeUtf8 decoded)
-- Left _ -> "Error decoding Base64 for URLs.\n"
-- enc64url :: String -> String
-- enc64url = C.unpack . B64U.encode . BSU.fromString
dec64url :: B.ByteString -> B.ByteString
dec64url input = case B64U.decode input of
Right byteString -> byteString
Left _ -> BC.pack "Error: Invalid Base64URL input"
enc64url :: B.ByteString -> B.ByteString
enc64url = B64U.encode