-
Notifications
You must be signed in to change notification settings - Fork 0
/
keywrap.go
114 lines (98 loc) · 2.24 KB
/
keywrap.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package aes
import (
"bytes"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"os"
"bandr.me/p/pocryp/internal/aes/kw"
)
func KeyWrapCmd(args ...string) error {
fset := flag.NewFlagSet("aes-keywrap", flag.ContinueOnError)
fset.Usage = func() {
fmt.Fprint(os.Stderr, `Usage: pocryp aes-keywrap [-w/-u] -key/-key-file [-in INPUT] [-out OUTPUT]
Wrap/Unwrap INPUT to OUTPUT using AES-KEYWRAP.
If -in is not specified, stdin will be read.
If -out is not specified, the output will be printed to stdout.
Options:
`)
fset.PrintDefaults()
}
fWrap := fset.Bool("w", false, "Wrap the input to the output. Default if omitted.")
fUnwrap := fset.Bool("u", false, "Unwrap the input to the output.")
fOutput := fset.String("out", "", "Write the result to the file at path OUTPUT.")
fInput := fset.String("in", "", "Read data from the file at path INPUT.")
fKey := fset.String("key", "", "Key as hex.")
fKeyFile := fset.String("key-file", "", "File which contains the key as binary/text.")
if err := fset.Parse(args); err != nil {
return err
}
if *fKey == "" && *fKeyFile == "" {
fset.Usage()
return errors.New("no key specified, use -k or --key-file to specify it")
}
if *fKey != "" && *fKeyFile != "" {
fset.Usage()
return errors.New("cannot use -k and --key-file at the same time")
}
var key []byte
if *fKey != "" {
b, err := hex.DecodeString(*fKey)
if err != nil {
return err
}
key = b
}
if *fKeyFile != "" {
b, err := os.ReadFile(*fKeyFile)
if err != nil {
return err
}
key = b
}
var r io.Reader
if *fInput == "" {
r = os.Stdin
} else {
f, err := os.Open(*fInput)
if err != nil {
return err
}
defer f.Close()
r = f
}
var w io.Writer
if *fOutput == "" {
w = os.Stdout
} else {
f, err := os.Create(*fOutput)
if err != nil {
return err
}
defer f.Close()
w = f
}
var input bytes.Buffer
if _, err := io.Copy(&input, r); err != nil {
return err
}
var output []byte
var err error
switch {
case *fWrap:
output, err = kw.Wrap(key, input.Bytes())
case *fUnwrap:
output, err = kw.Unwrap(key, input.Bytes())
default:
output, err = kw.Wrap(key, input.Bytes())
}
if err != nil {
return err
}
if _, err := io.Copy(w, bytes.NewBuffer(output)); err != nil {
return err
}
return nil
}