File: Padding.hs

package info (click to toggle)
haskell-cryptonite 0.30-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,372 kB
  • sloc: ansic: 22,009; haskell: 18,423; makefile: 8
file content (65 lines) | stat: -rw-r--r-- 2,187 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
-- |
-- Module      : Crypto.Data.Padding
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : unknown
--
-- Various cryptographic padding commonly used for block ciphers
-- or asymmetric systems.
--
module Crypto.Data.Padding
    ( Format(..)
    , pad
    , unpad
    ) where

import           Data.ByteArray (ByteArray, Bytes)
import qualified Data.ByteArray as B

-- | Format of padding
data Format =
      PKCS5     -- ^ PKCS5: PKCS7 with hardcoded size of 8
    | PKCS7 Int -- ^ PKCS7 with padding size between 1 and 255
    | ZERO Int  -- ^ zero padding with block size
    deriving (Show, Eq)

-- | Apply some pad to a bytearray
pad :: ByteArray byteArray => Format -> byteArray -> byteArray
pad  PKCS5     bin = pad (PKCS7 8) bin
pad (PKCS7 sz) bin = bin `B.append` paddingString
  where
    paddingString = B.replicate paddingByte (fromIntegral paddingByte)
    paddingByte   = sz - (B.length bin `mod` sz)
pad (ZERO sz)  bin = bin `B.append` paddingString
  where
    paddingString = B.replicate paddingSz 0
    paddingSz
      | len == 0   =  sz
      | m == 0     =  0
      | otherwise  =  sz - m
    m = len `mod` sz
    len = B.length bin

-- | Try to remove some padding from a bytearray.
unpad :: ByteArray byteArray => Format -> byteArray -> Maybe byteArray
unpad  PKCS5     bin = unpad (PKCS7 8) bin
unpad (PKCS7 sz) bin
    | len == 0                           = Nothing
    | (len `mod` sz) /= 0                = Nothing
    | paddingSz < 1 || paddingSz > len   = Nothing
    | paddingWitness `B.constEq` padding = Just content
    | otherwise                          = Nothing
  where
    len         = B.length bin
    paddingByte = B.index bin (len - 1)
    paddingSz   = fromIntegral paddingByte
    (content, padding) = B.splitAt (len - paddingSz) bin
    paddingWitness     = B.replicate paddingSz paddingByte :: Bytes
unpad (ZERO sz)  bin
    | len == 0                           = Nothing
    | (len `mod` sz) /= 0                = Nothing
    | B.index bin (len - 1) /= 0         = Just bin
    | otherwise                          = Nothing
  where
    len         = B.length bin