aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 75199f2c82562413fc59b79cfea7892a39550595 (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
// SPDX-FileCopyrightText: © 2021 Grégoire Duchêne <gduchene@awhk.org>
// SPDX-License-Identifier: ISC

package main

import (
	"bytes"
	"encoding/base64"
	"flag"
	"fmt"
	"io"
	"os"

	"github.com/hashicorp/vault/shamir"
)

var (
	combine = flag.Bool("c", false, "combine instead of split")
	parts   = flag.Int("p", 10, "parts to split the secret into")
	thres   = flag.Int("t", 2, "threshold required to reconstruct the secret")
)

func main() {
	flag.Parse()

	buf, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to read the secret:", err)
		os.Exit(1)
	}

	if !*combine {
		parts, err := shamir.Split(buf, *parts, *thres)
		if err != nil {
			fmt.Fprintln(os.Stderr, "failed to split the secret:", err)
			os.Exit(1)
		}
		for _, part := range parts {
			fmt.Println(base64.StdEncoding.EncodeToString(part))
		}
		return
	}

	parts := [][]byte{}
	for _, buf := range bytes.Split(buf, []byte("\n")) {
		if len(buf) == 0 {
			continue
		}
		part := make([]byte, base64.StdEncoding.DecodedLen(len(buf)))
		n, err := base64.StdEncoding.Decode(part, buf)
		if err != nil {
			fmt.Fprintln(os.Stderr, "failed to decode a part:", err)
			os.Exit(1)
		}
		parts = append(parts, part[:n])
	}
	sec, err := shamir.Combine(parts)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to combine parts:", err)
		os.Exit(1)
	}
	fmt.Print(string(sec))
}