vincenthz / hs-cipher-aes

DEPRECATED - use cryptonite - a comprehensive fast AES implementation for haskell that supports aesni and advanced cryptographic modes.
Other
21 stars 15 forks source link

Problem with IV on decryption #23

Open nd2s opened 10 years ago

nd2s commented 10 years ago

I'm new to Haskell and having problem using your package. I'm not sure if that is a bug in your lib of if i'm just using it incorrectly.

I'm using a custom encrypt method that's appending the IV to the encrypted string, and a custom decrypt that's splitting them again for decryptCBC.

Minimal code example:

module Test where

import           Crypto.Cipher.AES
import qualified Data.ByteString as BSw
import qualified Data.ByteString.Char8 as BS

encrypt :: AES -> BS.ByteString -> BS.ByteString
encrypt aes t = randIV `BS.append` (encryptCBC aes randIV t)

decrypt :: AES -> BS.ByteString -> BS.ByteString
decrypt aes t = decryptCBC aes (fst $ encSplit t) (snd $ encSplit t)

 -- Splits encryptedAES string into (IV, encrypted_string).
encSplit :: BS.ByteString -> (BS.ByteString, BS.ByteString)
encSplit s = BS.splitAt aesIVLength s

-- Length of AES IV in bytes.
aesIVLength :: Int
aesIVLength = 8

-- dummy IV
randIV :: BS.ByteString
randIV = BSw.replicate aesIVLength 1

-- dummy key
aesKey :: BS.ByteString
aesKey = BSw.pack [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

makeKey :: BS.ByteString -> AES
makeKey = initAES

My problem is now that decrypt does no decrypt correctly. See my ghci session:

λ> let aes = makeKey aesKey

-- Encrypt some string. First 8 bytes are appended IV.
λ> let encStr = encrypt aes $ BS.pack "1234567890123456"
λ> encStr
"\SOH\SOH\SOH\SOH\SOH\SOH\SOH\SOHjd\138\197\206\152\193\170kp\129\&6\246\248\&3\246"

-- Split it into 8 byte IV and encrypted message.
λ> encSplit encStr
("\SOH\SOH\SOH\SOH\SOH\SOH\SOH\SOH","jd\138\197\206\152\193\170kp\129\&6\246\248\&3\246")

-- Decrypt method (that uses encSplit internally) does not decrypt correctly because of fst value in pair (the IV).
λ> decrypt aes encStr
"123456783\ETB\180\245\253\172\244\156"

-- ...But it works using the original IV.
λ> decryptCBC aes randIV $ snd $ encSplit encStr
"1234567890123456"

Any idea why it's not working with the IV I got from splitting the ByteString?

nd2s commented 10 years ago

Hi,

no idea why this doesn't show up as ticket comment...

But that did the trick - thank you very much! Stupid mistake.

Library should check for correct length and throw an exception on wrong IV, though...

Mandag 12 mai 2014 09:26:25 skrev Thomas M. DuBuisson:

AES encrypts in blocks of 16 bytes (128 bits), not 8. Fix your invalid aesIVLength constant and you should see the correct output:

*Test> let encStr = encrypt aes $ BS.pack "1234567890123456"
*Test> decrypt aes encStr
"1234567890123456"
*Test>

Reply to this email directly or view it on GitHub: https://github.com/vincenthz/hs-cipher-aes/issues/23#issuecomment-42854403