-
Notifications
You must be signed in to change notification settings - Fork 233
/
master_alikms_cipher.go
85 lines (73 loc) · 2.37 KB
/
master_alikms_cipher.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
package osscrypto
import (
"encoding/base64"
"encoding/json"
"fmt"
kms "github.com/aliyun/alibaba-cloud-sdk-go/services/kms"
)
// CreateMasterAliKms Create master key interface implemented by ali kms
// matDesc will be converted to json string
func CreateMasterAliKms(matDesc map[string]string, kmsID string, kmsClient *kms.Client) (MasterCipher, error) {
var masterCipher MasterAliKmsCipher
if kmsID == "" || kmsClient == nil {
return masterCipher, fmt.Errorf("kmsID is empty or kmsClient is nil")
}
var jsonDesc string
if len(matDesc) > 0 {
b, err := json.Marshal(matDesc)
if err != nil {
return masterCipher, err
}
jsonDesc = string(b)
}
masterCipher.MatDesc = jsonDesc
masterCipher.KmsID = kmsID
masterCipher.KmsClient = kmsClient
return masterCipher, nil
}
// MasterAliKmsCipher ali kms master key interface
type MasterAliKmsCipher struct {
MatDesc string
KmsID string
KmsClient *kms.Client
}
// GetWrapAlgorithm get master key wrap algorithm
func (mrc MasterAliKmsCipher) GetWrapAlgorithm() string {
return KmsAliCryptoWrap
}
// GetMatDesc get master key describe
func (mkms MasterAliKmsCipher) GetMatDesc() string {
return mkms.MatDesc
}
// Encrypt encrypt data by ali kms
// Mainly used to encrypt object's symmetric secret key and iv
func (mkms MasterAliKmsCipher) Encrypt(plainData []byte) ([]byte, error) {
// kms Plaintext must be base64 encoded
base64Plain := base64.StdEncoding.EncodeToString(plainData)
request := kms.CreateEncryptRequest()
request.RpcRequest.Scheme = "https"
request.RpcRequest.Method = "POST"
request.RpcRequest.AcceptFormat = "json"
request.KeyId = mkms.KmsID
request.Plaintext = base64Plain
response, err := mkms.KmsClient.Encrypt(request)
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(response.CiphertextBlob)
}
// Decrypt decrypt data by ali kms
// Mainly used to decrypt object's symmetric secret key and iv
func (mkms MasterAliKmsCipher) Decrypt(cryptoData []byte) ([]byte, error) {
base64Crypto := base64.StdEncoding.EncodeToString(cryptoData)
request := kms.CreateDecryptRequest()
request.RpcRequest.Scheme = "https"
request.RpcRequest.Method = "POST"
request.RpcRequest.AcceptFormat = "json"
request.CiphertextBlob = string(base64Crypto)
response, err := mkms.KmsClient.Decrypt(request)
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(response.Plaintext)
}