Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created February 12, 2011 15:56
Show Gist options
  • Save thsutton/823836 to your computer and use it in GitHub Desktop.
Save thsutton/823836 to your computer and use it in GitHub Desktop.
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as C (pack, unpack)
import qualified Data.ByteString.Lazy as L (fromChunks)
import qualified Data.ByteString.Lazy.Char8 as LC (pack)
import Data.Digest.Pure.SHA (hmacSha1, showDigest)
import Data.List (sort)
import Network.URL (URL(..), importURL, exportURL, exportParams, add_param)
-- | Calculate the SHA-1 HMAC of the parameters and include it as the parameter "h".
signParameters :: ByteString -- | The key for HMAC.
-> URL -- | The URL to sign.
-> URL
signParameters key url =
let params = LC.pack $ exportParams $ sort $ url_params url
sig = showDigest $ hmacSha1 (L.fromChunks [key]) params
in add_param url ("h", sig)
-- | Sign a URL.
--
-- Returned Nothing when importURL is unable to parse the input URL.
signURL :: ByteString -- ^ The key for HMAC.
-> ByteString -- ^ The URL to be signed.
-> Maybe ByteString
signURL key url = do
url' <- importURL $ C.unpack url
let params = LC.pack $ exportParams $ sort $ url_params url'
let sig = showDigest $ hmacSha1 (L.fromChunks [key]) params
let url'' = add_param url' ("h", sig)
return $ C.pack $ exportURL $ url''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment