diff --git a/Crypto/Data/Padding.hs b/Crypto/Data/Padding.hs index 8bea760..66ed160 100644 --- a/Crypto/Data/Padding.hs +++ b/Crypto/Data/Padding.hs @@ -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 diff --git a/tests/Padding.hs b/tests/Padding.hs index a3af7cb..f7be773 100644 --- a/tests/Padding.hs +++ b/tests/Padding.hs @@ -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)