-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassword.go
45 lines (37 loc) · 1.29 KB
/
password.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
package secgen
import (
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"math/big"
"strings"
)
const charset = "abcdedfghijklmnopqrstABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // a-z A-Z 0-9
var charsetlen = big.NewInt(57)
// Password generates secure password
func Password(length int) string {
var password strings.Builder
for i := 0; i < length; i++ {
index, _ := rand.Int(rand.Reader, charsetlen)
password.WriteByte(charset[index.Int64()])
}
return password.String()
}
// Passphrase generates secure passphrase, based on shared secret and salt
func Passphrase(sharedSecret, salt string) string {
hash := sha512.Sum512([]byte(sharedSecret + salt))
return base64.StdEncoding.EncodeToString(hash[:])[:64]
}
// Base64Bytes generates secure bytes with the given length and returns it as a base64 string
func Base64Bytes(length int) string {
randomBytes := make([]byte, length)
rand.Read(randomBytes) //nolint:errcheck // nothing could be done anyway
return base64.StdEncoding.EncodeToString(randomBytes)
}
// HexBytes generates secure bytes with the given length and returns it as a hex string
func HexBytes(length int) string {
randomBytes := make([]byte, length)
rand.Read(randomBytes) //nolint:errcheck // nothing could be done anyway
return hex.EncodeToString(randomBytes)
}