-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
66 lines (60 loc) · 1.31 KB
/
util.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
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
)
// Display an error and terminate the application.
func abortWithError(err error) {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
// Open the input file. If filename is empty, return STDIN instead.
func openInput(filename string) (*os.File, error) {
if filename == "" {
return os.Stdin, nil
}
return os.Open(filename)
}
// Open the output file. If filename is empty, return STDOUT instead.
func openOutput(filename string) (*os.File, error) {
if filename == "" {
return os.Stdout, nil
}
return os.Create(filename)
}
// Generate a new pre-shared key of the requested size.
func generateKey(filename string, size int) ([]byte, error) {
f, err := os.Create(filename)
if err != nil {
return nil, err
}
defer f.Close()
b := make([]byte, size)
_, err = rand.Read(b)
if err != nil {
return nil, err
}
w := base64.NewEncoder(base64.StdEncoding, f)
defer w.Close()
_, err = w.Write(b)
if err != nil {
return nil, err
}
return b, nil
}
// Open the pre-shared key.
func openKey(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
b, err := ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
if err != nil {
return nil, err
}
return b, nil
}