-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (71 loc) · 1.47 KB
/
main.go
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
79
80
81
82
83
84
85
86
87
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"html/template"
"log"
"os"
"golang.org/x/crypto/pbkdf2"
)
const (
ArgProgram = iota
ArgUser
ArgPassword
ArgCount
)
func main() {
if len(os.Args) != ArgCount {
log.Fatalf("Usage: %s <user> <password>\n", os.Args[ArgProgram])
}
password, err := ScramSHA256Auth(os.Args[ArgPassword])
if err != nil {
log.Fatal(err)
}
tmpl, err := template.New("sql").Parse(sql)
if err != nil {
log.Fatal(err)
}
_ = tmpl.Execute(os.Stdout, struct {
User string
Password string
}{
User: os.Args[ArgUser],
Password: password,
})
}
const sql = `CREATE ROLE "{{.User}}" WITH
LOGIN
PASSWORD '{{.Password}}';
`
const (
SaltSize = 16
IterCount = 4096
ScramSHA256Name = "SCRAM-SHA-256"
clientKeyName = "Client Key"
serverKeyName = "Server Key"
)
func ScramSHA256Auth(password string) (string, error) {
salt := make([]byte, SaltSize)
if _, err := rand.Read(salt); err != nil {
return "", err
}
saltedPassword := pbkdf2.Key([]byte(password), salt, IterCount, sha256.Size, sha256.New)
h := hmac.New(sha256.New, saltedPassword)
h.Write([]byte(clientKeyName))
clientKey := h.Sum(nil)
storedKey := sha256.Sum256(clientKey)
h.Reset()
h.Write([]byte(serverKeyName))
serverKey := h.Sum(nil)
enc := base64.StdEncoding.EncodeToString
return fmt.Sprintf("%s$%d:%s$%s:%s",
ScramSHA256Name,
IterCount,
enc(salt),
enc(storedKey[:]),
enc(serverKey),
), nil
}