Search code examples
haskellencryptionxor

Haskell Encryption Program


I am trying to write a program called encrypt that transforms a text file by scrambling each of its characters. This is achieved by providing a key (string) as a command line argument which is used to encode the input. Thus:

cat txtfile.txt | ./encrypt XXAYSAAZZ will encrypt the text by matching up the text with the key infinitely.

The..
XXA..
The World...
XXAYSAAZZ etc..
The World is Not Enough etc...
XXAYSAAZZXXAYSAAZZXXAYS etc...

And "exclusively-or-ing" the corresponding characters. But due to the nature of XOR I am supposed to be able to retain the original text by doing this:

cat txtfile.txt | ./encrypt XXAYSAAZZ | ./scramble XXAYSAAZZ

So far I have got this:

module Main where
import System
import Data.Char

main = do arg1 <- getArgs  
       txt  <- getContents 
       putStr((snd (unzip (zip (txt) (cycle(head arg1))))))

The xor function is located in Data.Bits.

I have tried using xor many times, but I am not sure how I would decrypt the text.

Please give some ideas.

So if the text was:

cat txtfile.txt | ./encrypt XXAYSAAZZ

"Hello World, Goodbye World" it should replace the text with the KEY (XXAYSAAZZ) infinitely i.e.

"XXAYSAAZZXXAYSAAZZXXAYSAAZ" and cat txtfile.txt | ./encrypt XXAYSAAZZ | ./encrypt XXAYSAAZZ should give back:

"Hello World, Goodbye World" 

If you call it twice it returns the original string.


Solution

  • This

    putStr((snd (unzip (zip (txt) (cycle(head arg1))))))
    

    just replaces the text with an equally long part of the cycled key. It is impossible to retrieve the text from that, since all information except its length has been lost.

    It seems that the encryption is intended to xor each text character with the paired key character (cycling the key to get sufficient length).

    For such a scheme, the zipWith function is intended,

    zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    

    here,

    let cypher = zipWith xor text (cycle key)
    

    But you should check that the key is nonempty, or it won't work. However, there's another problem you have to solve, there is no

    instance Bits Char where
    

    defined (and since so far Bits has a superclass constraint of Num - that is slated to be removed - there can't be). So you need to transform your key and plaintext to a type with a Bits instance, the easiest way is using the Enum instance of Char

    main = do
      (key:_) <- getArgs
      if null key
         then error "encryption key must be nonempty"
         else do
           let xkey = map fromEnum (cycle key)
           plain <- getContents
           let cypher = map toEnum (zipWith xor xkey $ map fromEnum plain)
           putStr cypher