summaryrefslogtreecommitdiff
path: root/lib/PEM.hs
diff options
context:
space:
mode:
Diffstat (limited to 'lib/PEM.hs')
-rw-r--r--lib/PEM.hs34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/PEM.hs b/lib/PEM.hs
new file mode 100644
index 0000000..e07b3d4
--- /dev/null
+++ b/lib/PEM.hs
@@ -0,0 +1,34 @@
1{-# LANGUAGE OverloadedStrings #-}
2module PEM where
3
4import Data.Monoid
5import qualified Data.ByteString.Lazy as LW
6import qualified Data.ByteString.Lazy.Char8 as L
7import Control.Monad
8import Control.Applicative
9import qualified Codec.Binary.Base64 as Base64
10import ScanningParser
11
12data PEMBlob = PEMBlob { pemType :: L.ByteString
13 , pemBlob :: L.ByteString
14 }
15 deriving (Eq,Show)
16
17pemParser mtyp = ScanningParser (maybe fndany fndtyp mtyp) pbdy
18 where
19 hdr typ = "-----BEGIN " <> typ <> "-----"
20 fndtyp typ bs = if bs==hdr typ then Just typ else Nothing
21 fndany bs = do
22 guard $ "-----BEGIN " `L.isPrefixOf` bs
23 let x0 = L.drop 11 bs
24 guard $ "-----" `LW.isSuffixOf` x0
25 let typ = L.take (L.length x0 - 5) x0
26 return typ
27
28 pbdy typ xs = (mblob, drop 1 rs)
29 where
30 (ys,rs) = span (/="-----END " <> typ <> "-----") xs
31 mblob = PEMBlob typ <$> LW.pack <$> Base64.decode (L.unpack dta)
32 dta = case ys of
33 [] -> ""
34 dta_lines -> L.concat dta_lines