GaloisInc / RSA

Haskell RSA Library
Other
20 stars 7 forks source link

Arbitrary-sized messages not working #8

Closed quchen closed 10 years ago

quchen commented 11 years ago

The docs claim that encrypt can handle messages of arbitrary size, splitting them as appropriate to fit them into RSA. In the current implementation however, long messages error.

import Crypto.Random
import Codec.Crypto.RSA
import Data.Binary

main = do

      g <- newGenIO :: IO SystemRandom

      let msg = "Hello, World!"

      putStr "1024 bit key pair: "
      g'   <- cryptoTest g  msg 1024

      putStr "128 bit key pair: "
      _g'' <- cryptoTest g' msg 128

      return ()

-- | Generate a RSA key pair of a given length, and 
--   encrypt/decrypt a provided message with it.
--   Prints the decrypted message.
cryptoTest :: CryptoRandomGen gen
           => gen    -- ^ RNG
           -> String -- ^ Message
           -> Int    -- ^ RSA modulus length
           -> IO gen -- ^ Modified generator
cryptoTest g msg n =
      let (public, private, g') = generateKeyPair g n
          (encrypted, g'') = encrypt g' public (encode msg)
          decrypted = decode (decrypt private encrypted) :: String
      in  putStrLn decrypted >> return g''

Output:

> runhaskell test.hs
1024 bit key pair: Hello, World!
128 bit key pair: test.hs: message too long (rsaes_oaep_encrypt)
acw commented 10 years ago

It turns out that I had missed something in my reading of the RSA specification (or, rather, I did it correctly, but didn't make the obvious inference). According to the specification, certain cryptographic functions require certain minimum key sizes. I've reflected these constraints in the updated Haddock comments for RSA version 2.

In your particular example, the hash size used with the default 'encrypt' function requires a key size of at least 512 bits, I believe. If you'd rather use a smaller key (like 128 bits) you may be able to do it, but you'll have to find a hash function with a smaller hash size.

This isn't fixable in the traditional sense (because the behavior is according to spec), but I've updated the documentation to better describe the constraints.