Skip to content

Instantly share code, notes, and snippets.

@kalloc
Last active August 29, 2015 14:27
Show Gist options
  • Save kalloc/aa5716b705ed3e5ab358 to your computer and use it in GitHub Desktop.
Save kalloc/aa5716b705ed3e5ab358 to your computer and use it in GitHub Desktop.
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Bits
import System.Environment
import Data.Char (ord, chr)
import Math.NumberTheory.GCD (extendedGCD)
import System.Exit
p = 0x87c296ed480f9ab17885decd31197d617779c0dac70c3234996e1
q = 0x4fa84812157119acc8ecca98c404b2e5ee24ce18f60ea818091895
e = 0x10001
parse :: [String]->IO String
parse ["-h"] = usage >> exit
parse [] = getContents
parse fs = concat `fmap` mapM readFile fs
usage :: IO()
usage = putStrLn "Usage: rsa -h\n"
exit :: IO String
exit = exitWith ExitSuccess
-- die :: IO()
-- die = exitWith (ExitFailure 1)
mod' :: Integer->Integer->Integer->Integer
mod' x y z = mod_' x y z 1
mod_' :: Integer->Integer->Integer->Integer->Integer
mod_' _ 0 _ number =
number
mod_' x y z number =
let
number' = if (y `mod` 2) == 1 then number * x `mod` z else number
y' = y `shiftR` 1
x' = x * x `mod` z
in
mod_' x' y' z number'
encrypt :: Integer->Integer
encrypt message =
let
n = p * q
in
mod' message e n
decrypt :: Integer->Integer
decrypt message =
let
n = p * q
euler = (p - 1) * (q - 1)
(_, x, _) = e `extendedGCD` euler
d = euler + x
in
mod' message d n
process :: Integer->Integer
process = encrypt
toInt :: String -> Integer
toInt string = toInteger $ foldl (+) 0 $ zipWith (\x y -> y `shiftL` ( (x - 1) * 8) ) [1..] $ reverse $ map toInteger $ map ord string
toData' :: Integer->[Char]->[Char]
toData' 0 chars = chars
toData' n chars =
let next_n = n `shiftR` 8
next_char = chr $ fromInteger(n - ((n `shiftR` 8) `shiftL` 8 ))
next_chars = [next_char] ++ chars
in
toData' next_n next_chars
toData :: Integer->String
toData int = toData' int []
main :: IO()
main = getArgs >>= parse >>= putStr . toData . process . toInt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment