aboutsummaryrefslogtreecommitdiff
path: root/internal/utils/utils.go
blob: a453107a04d6b5e01c552762539993309e365698 (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
package utils

import (
	"crypto"
	"crypto/ed25519"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"git.sigsum.org/sigsum-go/pkg/log"
	"git.sigsum.org/sigsum-go/pkg/types"
)

// TODO: Move SetupLogging to sigsum-go/pkg/log

func SetupLogging(logFile, logLevel string, logColor bool) error {
	if len(logFile) != 0 {
		f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			return err
		}
		log.SetOutput(f)
	}

	switch logLevel {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	case "warning":
		log.SetLevel(log.WarningLevel)
	case "error":
		log.SetLevel(log.ErrorLevel)
	default:
		return fmt.Errorf("invalid logging level %s", logLevel)
	}

	log.SetColor(logColor)
	return nil
}

func PubkeyFromHexString(pkhex string) (*types.PublicKey, error) {
	pkbuf, err := hex.DecodeString(pkhex)
	if err != nil {
		return nil, fmt.Errorf("DecodeString: %v", err)
	}

	var pk types.PublicKey
	if n := copy(pk[:], pkbuf); n != types.PublicKeySize {
		return nil, fmt.Errorf("invalid pubkey size: %v", n)
	}

	return &pk, nil
}

func NewLogIdentity(keyFile string) (crypto.Signer, string, error) {
	buf, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return nil, "", err
	}
	if buf, err = hex.DecodeString(strings.TrimSpace(string(buf))); err != nil {
		return nil, "", fmt.Errorf("DecodeString: %v", err)
	}
	sk := crypto.Signer(ed25519.NewKeyFromSeed(buf))
	vk := sk.Public().(ed25519.PublicKey)
	return sk, hex.EncodeToString([]byte(vk[:])), nil
}