You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.2 KiB

4 years ago
3 years ago
4 years ago
  1. package coscrypto
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
  7. "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
  8. kms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/kms/v20190118"
  9. "git.ouxuan.net/tommy/cos-go-sdk-v5"
  10. )
  11. const (
  12. KMSEndPoint = "kms.tencentcloudapi.com"
  13. )
  14. type MasterKMSCipher struct {
  15. Client *kms.Client
  16. KmsId string
  17. MatDesc string
  18. }
  19. func NewKMSClient(cred *cos.Credential, region string) (*kms.Client, error) {
  20. if cred == nil {
  21. fmt.Errorf("credential is nil")
  22. }
  23. credential := common.NewTokenCredential(
  24. cred.SecretID,
  25. cred.SecretKey,
  26. cred.SessionToken,
  27. )
  28. cpf := profile.NewClientProfile()
  29. cpf.HttpProfile.Endpoint = KMSEndPoint
  30. client, err := kms.NewClient(credential, region, cpf)
  31. return client, err
  32. }
  33. func CreateMasterKMS(client *kms.Client, kmsId string, desc map[string]string) (MasterCipher, error) {
  34. if kmsId == "" || client == nil {
  35. return nil, fmt.Errorf("KMS ID is empty or kms client is nil")
  36. }
  37. var kmsCipher MasterKMSCipher
  38. var jdesc string
  39. if len(desc) > 0 {
  40. bs, err := json.Marshal(desc)
  41. if err != nil {
  42. return nil, err
  43. }
  44. jdesc = string(bs)
  45. }
  46. kmsCipher.Client = client
  47. kmsCipher.KmsId = kmsId
  48. kmsCipher.MatDesc = jdesc
  49. return &kmsCipher, nil
  50. }
  51. func (kc *MasterKMSCipher) Encrypt(plaintext []byte) ([]byte, error) {
  52. request := kms.NewEncryptRequest()
  53. request.KeyId = common.StringPtr(kc.KmsId)
  54. request.EncryptionContext = common.StringPtr(kc.MatDesc)
  55. request.Plaintext = common.StringPtr(base64.StdEncoding.EncodeToString(plaintext))
  56. resp, err := kc.Client.Encrypt(request)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return []byte(*resp.Response.CiphertextBlob), nil
  61. }
  62. func (kc *MasterKMSCipher) Decrypt(ciphertext []byte) ([]byte, error) {
  63. request := kms.NewDecryptRequest()
  64. request.CiphertextBlob = common.StringPtr(string(ciphertext))
  65. request.EncryptionContext = common.StringPtr(kc.MatDesc)
  66. resp, err := kc.Client.Decrypt(request)
  67. if err != nil {
  68. return nil, err
  69. }
  70. return base64.StdEncoding.DecodeString(*resp.Response.Plaintext)
  71. }
  72. func (kc *MasterKMSCipher) GetWrapAlgorithm() string {
  73. return CosKmsCryptoWrap
  74. }
  75. func (kc *MasterKMSCipher) GetMatDesc() string {
  76. return kc.MatDesc
  77. }