aboutsummaryrefslogtreecommitdiff
path: root/internal/util/util.go
blob: 4d5224580062aaad866a3dfb1ba5f358938abd6f (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
package util

import (
	"bytes"
	"crypto"
	"crypto/ed25519"
	"fmt"
	"io/ioutil"
	"os"

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

func BytesFromStdin() ([]byte, error) {
	b, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return nil, fmt.Errorf("util: read stdin: %v", err)
	}
	return b, nil
}

func HexFromStdin() ([]byte, error) {
	b, err := BytesFromStdin()
	if err != nil {
		return nil, err
	}
	b, err = hex.Deserialize(string(bytes.TrimSpace(b)))
	if err != nil {
		return nil, fmt.Errorf("util: parse stdin: %v", err)
	}
	return b, nil
}

func SignerFromHex(s string) (crypto.Signer, error) {
	b, err := hex.Deserialize(s)
	if err != nil {
		return nil, fmt.Errorf("util: parse key: %v", err)
	}
	if len(b) != ed25519.PrivateKeySize {
		return nil, fmt.Errorf("util: invalid private key size %d", len(b))
	}
	return ed25519.PrivateKey(b), nil
}

func FileHash(path string) (*types.Hash, error) {
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("util: read file %s: %v", path, err)
	}
	return types.HashFn(b), nil
}