master_alikms_cipher_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package osscrypto
  2. import (
  3. crypto_rand "crypto/rand"
  4. "encoding/base64"
  5. "io"
  6. "math/rand"
  7. "time"
  8. kms "github.com/aliyun/alibaba-cloud-sdk-go/services/kms"
  9. . "gopkg.in/check.v1"
  10. )
  11. func (s *OssCryptoBucketSuite) TestKmsClient(c *C) {
  12. rand.Seed(time.Now().UnixNano())
  13. kmsClient, err := kms.NewClientWithAccessKey(kmsRegion, kmsAccessID, kmsAccessKey)
  14. c.Assert(err, IsNil)
  15. // encrypte
  16. enReq := kms.CreateEncryptRequest()
  17. enReq.RpcRequest.Scheme = "https"
  18. enReq.RpcRequest.Method = "POST"
  19. enReq.RpcRequest.AcceptFormat = "json"
  20. enReq.KeyId = kmsID
  21. buff := make([]byte, 10)
  22. _, err = io.ReadFull(crypto_rand.Reader, buff)
  23. c.Assert(err, IsNil)
  24. enReq.Plaintext = base64.StdEncoding.EncodeToString(buff)
  25. enResponse, err := kmsClient.Encrypt(enReq)
  26. c.Assert(err, IsNil)
  27. // decrypte
  28. deReq := kms.CreateDecryptRequest()
  29. deReq.RpcRequest.Scheme = "https"
  30. deReq.RpcRequest.Method = "POST"
  31. deReq.RpcRequest.AcceptFormat = "json"
  32. deReq.CiphertextBlob = enResponse.CiphertextBlob
  33. deResponse, err := kmsClient.Decrypt(deReq)
  34. c.Assert(err, IsNil)
  35. c.Assert(deResponse.Plaintext, Equals, enReq.Plaintext)
  36. }
  37. func (s *OssCryptoBucketSuite) TestMasterAliKmsCipherSuccess(c *C) {
  38. kmsClient, err := kms.NewClientWithAccessKey(kmsRegion, kmsAccessID, kmsAccessKey)
  39. c.Assert(err, IsNil)
  40. masterCipher, _ := CreateMasterAliKms(matDesc, kmsID, kmsClient)
  41. var cd CipherData
  42. err = cd.RandomKeyIv(aesKeySize, ivSize)
  43. c.Assert(err, IsNil)
  44. cd.WrapAlgorithm = masterCipher.GetWrapAlgorithm()
  45. cd.CEKAlgorithm = KmsAliCryptoWrap
  46. cd.MatDesc = masterCipher.GetMatDesc()
  47. // EncryptedKey
  48. cd.EncryptedKey, err = masterCipher.Encrypt(cd.Key)
  49. // EncryptedIV
  50. cd.EncryptedIV, err = masterCipher.Encrypt(cd.IV)
  51. cloneData := cd.Clone()
  52. cloneData.Key, _ = masterCipher.Decrypt(cloneData.EncryptedKey)
  53. cloneData.IV, _ = masterCipher.Decrypt(cloneData.EncryptedIV)
  54. c.Assert(string(cd.Key), Equals, string(cloneData.Key))
  55. c.Assert(string(cd.IV), Equals, string(cloneData.IV))
  56. }
  57. func (s *OssCryptoBucketSuite) TestMasterAliKmsCipherError(c *C) {
  58. kmsClient, err := kms.NewClientWithAccessKey(kmsRegion, kmsAccessID, kmsAccessKey)
  59. c.Assert(err, IsNil)
  60. masterCipher, _ := CreateMasterAliKms(matDesc, kmsID, kmsClient)
  61. v := masterCipher.(MasterAliKmsCipher)
  62. v.KmsID = ""
  63. _, err = v.Encrypt([]byte("hellow"))
  64. c.Assert(err, NotNil)
  65. _, err = v.Decrypt([]byte("hellow"))
  66. c.Assert(err, NotNil)
  67. }