-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
80 lines (69 loc) · 2.21 KB
/
main.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
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
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package main provides a command line tool for creating signing keys
package main
import (
"crypto/rand"
"flag"
"fmt"
"os"
"golang.org/x/mod/sumdb/note"
"k8s.io/klog/v2"
)
var (
keyName = flag.String("key_name", "", "Name for the key identity.")
outPriv = flag.String("out_priv", "", "Output file for private key.")
outPub = flag.String("out_pub", "", "Output file for public key.")
print = flag.Bool("print", false, "Print private key, then public key, over 2 lines, to stdout.")
)
func main() {
klog.InitFlags(nil)
flag.Parse()
if len(*keyName) == 0 {
klog.Exit("--key_name required")
}
if !(*print) {
if len(*outPriv) == 0 || len(*outPub) == 0 {
klog.Exit("--print and/or --out_priv and --out_pub required.")
}
}
skey, vkey, err := note.GenerateKey(rand.Reader, *keyName)
if err != nil {
klog.Exitf("Unable to create key: %q", err)
}
if *print {
fmt.Println(skey)
fmt.Println(vkey)
}
if len(*outPriv) > 0 && len(*outPub) > 0 {
if err := writeFileIfNotExists(*outPriv, skey); err != nil {
klog.Exit(err)
}
if err := writeFileIfNotExists(*outPub, vkey); err != nil {
klog.Exit(err)
}
}
}
// writeFileIfNotExists writes key files. Ensures files do not already exist to avoid accidental overwriting.
func writeFileIfNotExists(filename string, key string) error {
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return fmt.Errorf("unable to create new key file %q: %w", filename, err)
}
_, err = file.WriteString(key)
if err != nil {
return fmt.Errorf("unable to write new key file %q: %w", filename, err)
}
return file.Close()
}