github.com/aliyun/aliyun-oss-go-sdk@v3.0.2+incompatible/oss/crypto/master_alikms_cipher.go (about) 1 package osscrypto 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "fmt" 7 8 kms "github.com/aliyun/alibaba-cloud-sdk-go/services/kms" 9 ) 10 11 // CreateMasterAliKms Create master key interface implemented by ali kms 12 // matDesc will be converted to json string 13 func CreateMasterAliKms(matDesc map[string]string, kmsID string, kmsClient *kms.Client) (MasterCipher, error) { 14 var masterCipher MasterAliKmsCipher 15 if kmsID == "" || kmsClient == nil { 16 return masterCipher, fmt.Errorf("kmsID is empty or kmsClient is nil") 17 } 18 19 var jsonDesc string 20 if len(matDesc) > 0 { 21 b, err := json.Marshal(matDesc) 22 if err != nil { 23 return masterCipher, err 24 } 25 jsonDesc = string(b) 26 } 27 28 masterCipher.MatDesc = jsonDesc 29 masterCipher.KmsID = kmsID 30 masterCipher.KmsClient = kmsClient 31 return masterCipher, nil 32 } 33 34 // MasterAliKmsCipher ali kms master key interface 35 type MasterAliKmsCipher struct { 36 MatDesc string 37 KmsID string 38 KmsClient *kms.Client 39 } 40 41 // GetWrapAlgorithm get master key wrap algorithm 42 func (mrc MasterAliKmsCipher) GetWrapAlgorithm() string { 43 return KmsAliCryptoWrap 44 } 45 46 // GetMatDesc get master key describe 47 func (mkms MasterAliKmsCipher) GetMatDesc() string { 48 return mkms.MatDesc 49 } 50 51 // Encrypt encrypt data by ali kms 52 // Mainly used to encrypt object's symmetric secret key and iv 53 func (mkms MasterAliKmsCipher) Encrypt(plainData []byte) ([]byte, error) { 54 // kms Plaintext must be base64 encoded 55 base64Plain := base64.StdEncoding.EncodeToString(plainData) 56 request := kms.CreateEncryptRequest() 57 request.RpcRequest.Scheme = "https" 58 request.RpcRequest.Method = "POST" 59 request.RpcRequest.AcceptFormat = "json" 60 61 request.KeyId = mkms.KmsID 62 request.Plaintext = base64Plain 63 64 response, err := mkms.KmsClient.Encrypt(request) 65 if err != nil { 66 return nil, err 67 } 68 return base64.StdEncoding.DecodeString(response.CiphertextBlob) 69 } 70 71 // Decrypt decrypt data by ali kms 72 // Mainly used to decrypt object's symmetric secret key and iv 73 func (mkms MasterAliKmsCipher) Decrypt(cryptoData []byte) ([]byte, error) { 74 base64Crypto := base64.StdEncoding.EncodeToString(cryptoData) 75 request := kms.CreateDecryptRequest() 76 request.RpcRequest.Scheme = "https" 77 request.RpcRequest.Method = "POST" 78 request.RpcRequest.AcceptFormat = "json" 79 request.CiphertextBlob = string(base64Crypto) 80 response, err := mkms.KmsClient.Decrypt(request) 81 if err != nil { 82 return nil, err 83 } 84 return base64.StdEncoding.DecodeString(response.Plaintext) 85 }