aes_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2021 Tencent Inc. All rights reserved.
  2. package utils
  3. import (
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/require"
  7. )
  8. const (
  9. testAESUtilAPIV3Key = "testAPIv3Key0000"
  10. testAESUtilCiphertext = "FsdXzxryWfKwvLJKf8LG/ToRPTRh8RN9wROC"
  11. testAESUtilPlaintext = "Hello World"
  12. testAESUtilNonce = "wCq51qZv4Yfg"
  13. testAESUtilAssociatedData = "Dl56FrqWQJF1t9LtC3vEUsniZKvbqdR8"
  14. )
  15. func TestDecryptAes256Gcm(t *testing.T) {
  16. type args struct {
  17. apiv3Key string
  18. associatedData string
  19. nonce string
  20. ciphertext string
  21. }
  22. tests := []struct {
  23. name string
  24. args args
  25. plaintext string
  26. wantErr bool
  27. }{
  28. {
  29. name: "decrypt success",
  30. args: args{
  31. apiv3Key: testAESUtilAPIV3Key,
  32. associatedData: testAESUtilAssociatedData,
  33. nonce: testAESUtilNonce,
  34. ciphertext: testAESUtilCiphertext,
  35. },
  36. wantErr: false,
  37. plaintext: testAESUtilPlaintext,
  38. },
  39. {
  40. name: "invalid base64 ciphertext",
  41. args: args{
  42. apiv3Key: testAESUtilAPIV3Key,
  43. associatedData: testAESUtilAssociatedData,
  44. nonce: testAESUtilNonce,
  45. ciphertext: "invalid cipher",
  46. },
  47. wantErr: true,
  48. },
  49. {
  50. name: "invalid ciphertext",
  51. args: args{
  52. apiv3Key: testAESUtilAPIV3Key,
  53. associatedData: testAESUtilAssociatedData,
  54. nonce: testAESUtilNonce,
  55. ciphertext: "SGVsbG8gV29ybGQK",
  56. },
  57. wantErr: true,
  58. },
  59. {
  60. name: "invalid aes key",
  61. args: args{
  62. apiv3Key: "not a aes key",
  63. associatedData: testAESUtilAssociatedData,
  64. nonce: testAESUtilNonce,
  65. ciphertext: testAESUtilCiphertext,
  66. },
  67. wantErr: true,
  68. },
  69. {
  70. name: "wrong aes key",
  71. args: args{
  72. apiv3Key: "testAPIv3Key1111",
  73. associatedData: testAESUtilAssociatedData,
  74. nonce: testAESUtilNonce,
  75. ciphertext: testAESUtilCiphertext,
  76. },
  77. wantErr: true,
  78. },
  79. }
  80. for _, tt := range tests {
  81. t.Run(
  82. tt.name, func(t *testing.T) {
  83. plaintext, err := DecryptAES256GCM(
  84. tt.args.apiv3Key, tt.args.associatedData, tt.args.nonce, tt.args.ciphertext,
  85. )
  86. require.Equal(t, tt.wantErr, err != nil)
  87. assert.Equal(t, tt.plaintext, plaintext)
  88. },
  89. )
  90. }
  91. }