A fork of Gitea (see branch `mj`) adding Majority Judgment Polls 𐄷 over Issues and Merge Requests. https://git.mieuxvoter.fr
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.4 KiB

  1. package pwn
  2. import (
  3. "crypto/sha1"
  4. "encoding/hex"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. )
  11. const passwordURL = "https://api.pwnedpasswords.com/range/"
  12. // CheckPassword returns the number of times a password has been compromised
  13. // Adding padding will make requests more secure, however is also slower
  14. // because artificial responses will be added to the response
  15. // For more information, see https://www.troyhunt.com/enhancing-pwned-passwords-privacy-with-padding/
  16. func (c *Client) CheckPassword(pw string, padding bool) (int, error) {
  17. if strings.TrimSpace(pw) == "" {
  18. return -1, ErrEmptyPassword{}
  19. }
  20. sha := sha1.New()
  21. sha.Write([]byte(pw))
  22. enc := hex.EncodeToString(sha.Sum(nil))
  23. prefix, suffix := enc[:5], enc[5:]
  24. req, err := newRequest(c.ctx, http.MethodGet, fmt.Sprintf("%s%s", passwordURL, prefix), nil)
  25. if err != nil {
  26. return -1, nil
  27. }
  28. if padding {
  29. req.Header.Add("Add-Padding", "true")
  30. }
  31. resp, err := c.http.Do(req)
  32. if err != nil {
  33. return -1, err
  34. }
  35. body, err := ioutil.ReadAll(resp.Body)
  36. if err != nil {
  37. return -1, err
  38. }
  39. defer resp.Body.Close()
  40. for _, pair := range strings.Split(string(body), "\n") {
  41. parts := strings.Split(pair, ":")
  42. if len(parts) != 2 {
  43. continue
  44. }
  45. if strings.EqualFold(suffix, parts[0]) {
  46. count, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
  47. if err != nil {
  48. return -1, err
  49. }
  50. return int(count), nil
  51. }
  52. }
  53. return 0, nil
  54. }