master_alikms_cipher.go 2.4 KB

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