Skip to content

Instantly share code, notes, and snippets.

@sebkinne
Created February 22, 2018 08:14
Show Gist options
  • Save sebkinne/c26064b27d26c44e8d13ed9e6582550c to your computer and use it in GitHub Desktop.
Save sebkinne/c26064b27d26c44e8d13ed9e6582550c to your computer and use it in GitHub Desktop.
Quickly check a password against the pwnedpasswords.com API
package main
import (
"bufio"
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
)
var APIURL = "https://api.pwnedpasswords.com"
func lookup(hash string) (int64, error) {
prefix := hash[:5]
postfix := hash[5:]
resp, err := http.Get(APIURL + "/range/" + prefix)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return 0, nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
for _, entry := range strings.Split(string(body), "\r\n") {
if string(entry[:35]) == strings.ToUpper(postfix) {
count, err := strconv.ParseInt(entry[36:], 10, 64)
if err != nil {
return 0, err
}
return count, nil
}
}
return 0, nil
}
func getPassword() ([]byte, error) {
reader := bufio.NewReader(os.Stdin)
bytes, err := reader.ReadBytes('\n')
if len(bytes) > 0 {
bytes = bytes[:len(bytes)-1]
}
return bytes, err
}
func getHash(password []byte) string {
hash := sha1.New()
hash.Write(password)
return hex.EncodeToString(hash.Sum(nil))
}
func main() {
fmt.Print("Enter a password: ")
password, err := getPassword()
if err != nil {
fmt.Println("[!] Error reading password")
os.Exit(1)
}
hash := getHash(password)
count, err := lookup(hash)
if err != nil {
fmt.Println("[!] There was an error, please try again " + err.Error())
os.Exit(1)
}
if count == 0 {
fmt.Println("[*] Password not found!")
} else {
fmt.Println("[*] Password found! You should probably stop using that..")
}
}
@jamesspi
Copy link

Thanks for this! I have a suggestion though :)

Could we mask/blank the password input perhaps?

Other than that, kudos!

@sebkinne
Copy link
Author

Should be able to clear the line / mask it with stars, yeah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment