This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathencryption.go
78 lines (63 loc) · 1.82 KB
/
encryption.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
package encryption
import (
"fmt"
"github.com/s7techlab/cckit/convert"
"github.com/s7techlab/cckit/router"
)
const TransientMapKey = `ENCODE_KEY`
// EncryptArgs convert args to [][]byte and encrypt args with key
func EncryptArgs(key []byte, args ...interface{}) ([][]byte, error) {
argBytes, err := convert.ArgsToBytes(args...)
if err != nil {
return nil, err
}
return EncryptArgsBytes(key, argBytes)
}
// EncryptArgsBytes encrypt args with key
func EncryptArgsBytes(key []byte, argsBytes [][]byte) ([][]byte, error) {
eArgs := make([][]byte, len(argsBytes))
for i, bb := range argsBytes {
encrypted, err := EncryptBytes(key, bb)
if err != nil {
return nil, fmt.Errorf(`encryption error: %w`, err)
}
eArgs[i] = encrypted
}
return eArgs, nil
}
// DecryptArgs decrypt args
func DecryptArgs(key []byte, args [][]byte) ([][]byte, error) {
dargs := make([][]byte, len(args))
for i, a := range args {
// do not try to decrypt init function
if i == 0 && string(a) == router.InitFunc {
dargs[i] = a
continue
}
decrypted, err := DecryptBytes(key, a)
if err != nil {
return nil, fmt.Errorf(`decryption error: %w`, err)
}
dargs[i] = decrypted
}
return dargs, nil
}
// Encrypt converts value to []byte and encrypts its with key
func Encrypt(key []byte, value interface{}) ([]byte, error) {
// TODO: customize IV
bb, err := convert.ToBytes(value)
if err != nil {
return nil, fmt.Errorf(`convert values to bytes: %w`, err)
}
return EncryptBytes(key, bb)
}
// Decrypt decrypts value with key
func Decrypt(key, value []byte) ([]byte, error) {
bb := make([]byte, len(value))
copy(bb, value)
return DecryptBytes(key, bb)
}
// TransientMapWithKey creates transient map with encrypting/decrypting key
func TransientMapWithKey(key []byte) map[string][]byte {
return map[string][]byte{TransientMapKey: key}
}