fix unpad of zero-padding and add tests.

This commit is contained in:
Kei Hibino 2016-06-08 22:57:35 +09:00
parent ec7e73401f
commit 7989dc71b0
2 changed files with 15 additions and 7 deletions

View File

@ -56,4 +56,10 @@ unpad (PKCS7 sz) bin
paddingSz = fromIntegral paddingByte
(content, padding) = B.splitAt (len - paddingSz) bin
paddingWitness = B.replicate paddingSz paddingByte :: Bytes
unpad (ZERO sz) bin = Nothing
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

View File

@ -14,9 +14,9 @@ cases =
]
zeroCases =
[ ("", 4, "\NUL\NUL\NUL\NUL")
, ("abcdef", 8, "abcdef\NUL\NUL")
, ("0123456789abcdef", 16, "0123456789abcdef")
[ ("", 4, "\NUL\NUL\NUL\NUL", Nothing)
, ("abcdef", 8, "abcdef\NUL\NUL", Nothing)
, ("0123456789abcdef", 16, "0123456789abcdef", Just "0123456789abcdef")
]
--instance Arbitrary where
@ -27,9 +27,11 @@ testPad n (inp, sz, padded) =
, eqTest "unpadded" (Just inp) (unpad (PKCS7 sz) padded)
]
testZeroPad :: Int -> (B.ByteString, Int, B.ByteString) -> TestTree
testZeroPad n (inp, sz, padded) =
testCase (show n) $ propertyHoldCase [ eqTest "padded" padded (pad (ZERO sz) inp) ]
testZeroPad :: Int -> (B.ByteString, Int, B.ByteString, Maybe B.ByteString) -> TestTree
testZeroPad n (inp, sz, padded, unpadded) =
testCase (show n) $ propertyHoldCase [ eqTest "padded" padded (pad (ZERO sz) inp)
, eqTest "unpadded" unpadded (unpad (ZERO sz) padded)
]
tests = testGroup "Padding"
[ testGroup "Cases" $ map (uncurry testPad) (zip [1..] cases)