diff options
Diffstat (limited to 'lib/PEM.hs')
-rw-r--r-- | lib/PEM.hs | 34 |
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 #-} | ||
2 | module PEM where | ||
3 | |||
4 | import Data.Monoid | ||
5 | import qualified Data.ByteString.Lazy as LW | ||
6 | import qualified Data.ByteString.Lazy.Char8 as L | ||
7 | import Control.Monad | ||
8 | import Control.Applicative | ||
9 | import qualified Codec.Binary.Base64 as Base64 | ||
10 | import ScanningParser | ||
11 | |||
12 | data PEMBlob = PEMBlob { pemType :: L.ByteString | ||
13 | , pemBlob :: L.ByteString | ||
14 | } | ||
15 | deriving (Eq,Show) | ||
16 | |||
17 | pemParser 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 | ||