forked from mxschmitt/golang-url-shortener
/
private.go
44 lines (39 loc) · 1.15 KB
/
private.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
package util
import (
"crypto/rand"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
var privateKey []byte
// CheckForPrivateKey checks if already an private key exists, if not it will
// be randomly generated and saved as a private.dat file in the data directory
func CheckForPrivateKey() error {
privateDatPath := filepath.Join(Config.DataDir, "private.dat")
privateDatContent, err := ioutil.ReadFile(privateDatPath)
if err == nil {
privateKey = privateDatContent
} else if os.IsNotExist(err) {
randomGeneratedKey := make([]byte, 256)
if _, err = rand.Read(randomGeneratedKey); err != nil {
return errors.Wrap(err, "could not read random bytes")
}
if err = ioutil.WriteFile(privateDatPath, randomGeneratedKey, 0644); err != nil {
return errors.Wrap(err, "could not write private key")
}
privateKey = randomGeneratedKey
} else if err != nil {
return errors.Wrap(err, "could not read private key")
}
return nil
}
// GetPrivateKey returns the private key
func GetPrivateKey() []byte {
switch backend := GetConfig().Backend; backend {
case "redis":
return []byte(GetConfig().Redis.SharedKey)
default:
return privateKey
}
}