summaryrefslogtreecommitdiff
path: root/PEM.hs
diff options
context:
space:
mode:
Diffstat (limited to 'PEM.hs')
-rw-r--r--PEM.hs34
1 files changed, 34 insertions, 0 deletions
diff --git a/PEM.hs b/PEM.hs
new file mode 100644
index 0000000..e6c8259
--- /dev/null
+++ b/PEM.hs
@@ -0,0 +1,34 @@
1{-# LANGUAGE OverloadedStrings #-}
2module PEM where
3
4import Data.Maybe
5import Data.Monoid
6import qualified Data.ByteString.Lazy as LW
7import qualified Data.ByteString.Lazy.Char8 as L
8import Control.Monad
9import Control.Applicative
10import qualified Codec.Binary.Base64 as Base64
11import ScanningParser
12
13data PEMBlob = PEMBlob { pemType :: L.ByteString
14 , pemBlob :: L.ByteString
15 }
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, 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 _:dta_lines -> L.concat dta_lines
34 [] -> ""