forked from Mastercard/client-encryption-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.go
70 lines (59 loc) · 2.04 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
package encryption
import (
"github.com/Duong2903/client-encryption-go/jwe"
"github.com/Jeffail/gabs/v2"
"strings"
)
func EncryptPayload(payload string, config jwe.JWEConfig) string {
jsonPayload, _ := gabs.ParseJSON([]byte(payload))
for jsonPathIn, jsonPathOut := range config.GetEncryptionPaths() {
jsonPayload = encryptPayloadPath(jsonPayload, jsonPathIn, jsonPathOut, config)
}
return jsonPayload.String()
}
func DecryptPayload(encryptedPayload string, config jwe.JWEConfig) string {
jsonPayload, _ := gabs.ParseJSON([]byte(encryptedPayload))
for jsonPathIn, jsonPathOut := range config.GetDecryptionPaths() {
jsonPayload = decryptPayloadPath(jsonPayload, jsonPathIn, jsonPathOut, config)
}
return jsonPayload.String()
}
func encryptPayloadPath(jsonPayload *gabs.Container, jsonPathIn string, jsonPathOut string, config jwe.JWEConfig) *gabs.Container {
joseHeader := jwe.JOSEHeader{
Alg: "RSA-OAEP-256",
Enc: "A256GCM",
Kid: config.GetEncryptionKeyFingerprint(),
Cty: "application/json",
}
payload, err := jwe.Encrypt(config, jsonPayload.Path(jsonPathIn).String(), joseHeader)
if err != nil {
panic(err)
}
if jsonPathIn == "$" {
jsonPayload = gabs.New()
} else {
jsonPayload.DeleteP(jsonPathIn)
}
jsonPathOut = jsonPathOut + "." + config.GetEncryptedValueFieldName()
jsonPayload.Set(payload, strings.Split(jsonPathOut, ".")...)
return jsonPayload
}
func decryptPayloadPath(jsonPayload *gabs.Container, jsonPathIn string, jsonPathOut string, config jwe.JWEConfig) *gabs.Container {
inJsonObject := jsonPayload.Path(jsonPathIn + "." + config.GetEncryptedValueFieldName()).Data().(string)
jweObject, err := jwe.ParseJWEObject(inJsonObject)
if err != nil {
panic(err)
}
decryptedPayload, err := jweObject.Decrypt(config)
if err != nil {
panic(err)
}
jsonDecryptedPayload, err := gabs.ParseJSON([]byte(decryptedPayload))
if jsonPathOut == "$" {
jsonPayload = jsonDecryptedPayload
} else {
jsonPayload.DeleteP(jsonPathIn)
jsonPayload.Set(jsonDecryptedPayload, strings.Split(jsonPathOut, ".")...)
}
return jsonPayload
}