Skip to content

Instantly share code, notes, and snippets.

@rhwlo
Last active December 27, 2015 23:18
Show Gist options
  • Save rhwlo/2cf4fc8a9fe580f4b1fe to your computer and use it in GitHub Desktop.
Save rhwlo/2cf4fc8a9fe580f4b1fe to your computer and use it in GitHub Desktop.
Haskell utility for training yourself on a new password.
import Control.Exception (bracket_)
import Control.Monad.Except (catchError, throwError)
import Data.ByteString.Lazy.Char8 (pack)
import Data.Digest.Pure.SHA (sha256)
import System.IO (hGetEcho, hSetEcho, hFlush, hGetLine, hPutStrLn, stdin, stdout, withFile, IOMode(ReadMode,WriteMode))
import System.IO.Error (isDoesNotExistError)
withEcho :: Bool -> IO a -> IO a
withEcho echo action = do
old <- hGetEcho stdin
bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
getPass :: IO String
getPass = withEcho False getLine
main :: IO ()
main = let
ssp :: String -> String
ssp = show . sha256 . pack
getPasswordIfDoesntExist :: IOError -> IO String
getPasswordIfDoesntExist err
| isDoesNotExistError err = do
pwSha <- passwordPrompt
withFile ".new_password" WriteMode (`hPutStrLn` pwSha)
return pwSha
| otherwise = throwError err
passwordPrompt :: IO String
passwordPrompt = do
putStr "Enter new password: " >> hFlush stdout
pwSha <- ssp <$> getPass
putStr "Verify new password: " >> hFlush stdout
verifySha <- ssp <$> getPass
if pwSha == verifySha then return pwSha else passwordPrompt
getPasswordSha :: IO String
getPasswordSha = catchError (withFile ".new_password" ReadMode hGetLine) getPasswordIfDoesntExist
in do
pwSha <- getPasswordSha
verifySha <- ssp <$> (putStr "Verify new password: " >> hFlush stdout >> getPass)
if pwSha == verifySha then putStrLn "\nCorrect." else putStrLn "\nIncorrect."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment