Skip to content

Instantly share code, notes, and snippets.

@pgergis
Created July 17, 2018 17:50
Show Gist options
  • Save pgergis/129bb2627528ee4b2e60462dd21fa506 to your computer and use it in GitHub Desktop.
Save pgergis/129bb2627528ee4b2e60462dd21fa506 to your computer and use it in GitHub Desktop.
Basic Crypto Math (Haskell)
--file: cryptoMath.hs
-- Cryptopals: http://cryptopals.com/sets/1
-- Hex encoding: [0..9][A..F]
-- B64 encoding: [A..Z][a..z][0..9][+][/][[=]]
-- Note: Each hex char is 4 bits; each b64 char is 6 bits
module CryptoMath where
import Numeric
import Data.Digits
import Data.Bits
type BaseMap = [(Char, Integer)]
b64IntMap :: BaseMap
b64IntMap = zip (['A'..'Z']++['a'..'z']++['0'..'9']++['+','/']) [0..63]
hexIntMap :: BaseMap
hexIntMap = zip (['0'..'9']++['a'..'f']) [0..15]
int2char :: Integer -> BaseMap -> Char
int2char _ [] = '?'
int2char n ((char, int):restMap) =
if int == n then char else int2char n restMap
hexStringToVal :: String -> Integer
hexStringToVal s = fst $ head $ readHex s
valToB64 :: Integer -> [Integer]
valToB64 v = digits 64 v
valToHex :: Integer -> [Integer]
valToHex v = digits 16 v
b64ToS :: [Integer] -> String
b64ToS [] = []
b64ToS (x:xs) = (int2char x b64IntMap) : b64ToS xs
hexToS :: [Integer] -> String
hexToS [] = []
hexToS (x:xs) = (int2char x hexIntMap) : hexToS xs
hexTo64 :: String -> String
hexTo64 s = b64ToS $ valToB64 $ hexStringToVal s
heXOR :: String -> String -> String
heXOR x y= hexToS $ valToHex $ (hexStringToVal x) `xor` (hexStringToVal y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment