This repository was archived by the owner on Apr 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcipher.go
More file actions
59 lines (49 loc) · 1.36 KB
/
cipher.go
File metadata and controls
59 lines (49 loc) · 1.36 KB
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
package flag
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"fmt"
)
// Cipher parses the encryption key as raw bytes (original behavior).
type Cipher struct {
cipher.AEAD
}
func (flag *Cipher) UnmarshalFlag(val string) error {
return unmarshalCipher(&flag.AEAD, []byte(val))
}
// CipherBase64 parses the encryption key as a base64-encoded string.
type CipherBase64 struct {
cipher.AEAD
}
func (flag *CipherBase64) UnmarshalFlag(val string) error {
keyBytes, err := base64.StdEncoding.DecodeString(val)
if err != nil {
return fmt.Errorf("failed to decode base64 encryption key: %s", err)
}
return unmarshalCipher(&flag.AEAD, keyBytes)
}
// CipherHex parses the encryption key as a hex-encoded string.
type CipherHex struct {
cipher.AEAD
}
func (flag *CipherHex) UnmarshalFlag(val string) error {
keyBytes, err := hex.DecodeString(val)
if err != nil {
return fmt.Errorf("failed to decode hex encryption key: %s", err)
}
return unmarshalCipher(&flag.AEAD, keyBytes)
}
// unmarshalCipher creates an AES-GCM cipher from the given key bytes.
func unmarshalCipher(aead *cipher.AEAD, key []byte) error {
block, err := aes.NewCipher(key)
if err != nil {
return fmt.Errorf("failed to construct AES cipher: %s", err)
}
*aead, err = cipher.NewGCM(block)
if err != nil {
return fmt.Errorf("failed to construct GCM: %s", err)
}
return nil
}