summaryrefslogtreecommitdiff
path: root/pwned.go
blob: a965c4dd36893a02adfe0f5bd37e61e87fab2779 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

// Adapted from https://github.com/lenartj/pwned-passwords
import (
	"crypto/sha1"
	"fmt"
	"io"
	"log"
	"os"
	"sort"
	"strings"
)

type pwdb struct {
	f           *os.File
	n           int
	rs          int
	hash_length int
}

func NewPWDB(fn string) (*pwdb, error) {
	f, err := os.Open(fn)
	if err != nil {
		return nil, err
	}

	stat, err := f.Stat()
	if err != nil {
		return nil, err
	}

	const rs = 63 // V2 has fixed width of 63 bytes
	if stat.Size()%rs != 0 {
		return nil, fmt.Errorf("Unexpected password file format (must be a text file with 63 char width starting with sha1)")
	}
	const hash_length = 40 // sha1 is 40 chars

	return &pwdb{f, int(stat.Size() / rs), rs, hash_length}, nil
}

func (db *pwdb) record(i int) string {
	b := make([]byte, db.hash_length)
	db.f.ReadAt(b, int64(i*db.rs))
	return string(b)
}

func (db *pwdb) SearchHash(hash string) bool {
	if len(hash) != db.hash_length {
		return false
	}
	needle := strings.ToUpper(hash)

	i := sort.Search(db.n, func(i int) bool {
		return db.record(i) >= needle
	})
	return i < db.n && db.record(i) == needle
}

func (db *pwdb) SearchPassword(password string) bool {
	h := sha1.New()
	io.WriteString(h, password)
	return db.SearchHash(fmt.Sprintf("%x", h.Sum(nil)))
}

func (db *pwdb) Close() {
	db.f.Close()
}

func IsPasswordCompromised(password string) bool {
	pwndDB, err := NewPWDB(pwman.PwnedDBFile)
	if err != nil {
		log.Println("ERROR", "pwnedb", err)
		return false
	}
	defer pwndDB.Close()

	return pwndDB.SearchPassword(password)
}