aboutsummaryrefslogtreecommitdiff
path: root/internal/fmtio/fmtio.go
blob: 84b1265b74cf2c99f6e0125354aa5aa89a6b954b (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
70
71
72
73
74
75
76
77
78
79
80
// package fmtio provides basic utilities to format input and output
package fmtio

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

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

func BytesFromStdin() ([]byte, error) {
	b, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return nil, err
	}
	return b, nil
}

// StringFromStdin reads bytes from stdin, parsing them as a string without
// leading and trailing white space
func StringFromStdin() (string, error) {
	b, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return "", err
	}
	return string(bytes.TrimSpace(b)), nil
}

func SignerFromHex(s string) (crypto.Signer, error) {
	b, err := hex.Deserialize(s)
	if err != nil {
		return nil, err
	}
	if n := len(b); n != ed25519.SeedSize {
		return nil, fmt.Errorf("invalid size %d", n)
	}
	return ed25519.NewKeyFromSeed(b), nil
}

func PublicKeyFromHex(s string) (pub types.PublicKey, err error) {
	b, err := hex.Deserialize(s)
	if err != nil {
		return pub, err
	}
	if n := len(b); n != types.PublicKeySize {
		return pub, fmt.Errorf("invalid size %d", n)
	}
	copy(pub[:], b)
	return
}

func KeyHashFromHex(s string) (h merkle.Hash, err error) {
	b, err := hex.Deserialize(s)
	if err != nil {
		return h, err
	}
	if n := len(b); n != merkle.HashSize {
		return h, fmt.Errorf("invalid size %d", n)
	}
	copy(h[:], b)
	return
}

func SignatureFromHex(s string) (sig types.Signature, err error) {
	b, err := hex.Deserialize(s)
	if err != nil {
		return sig, err
	}
	if n := len(b); n != types.SignatureSize {
		return sig, fmt.Errorf("invalid size %d", n)
	}
	copy(sig[:], b)
	return
}