crypto_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package crypto
  14. import (
  15. "testing"
  16. "github.com/lithammer/dedent"
  17. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  18. )
  19. func TestEncryptAndDecryptData(t *testing.T) {
  20. key1, err := CreateRandBytes(kubeadmconstants.CertificateKeySize)
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. key2, err := CreateRandBytes(kubeadmconstants.CertificateKeySize)
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. testData := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
  29. tests := map[string]struct {
  30. encryptKey []byte
  31. decryptKey []byte
  32. data []byte
  33. expectDecryptErr bool
  34. }{
  35. "can decrypt using the correct key": {
  36. encryptKey: key1,
  37. decryptKey: key1,
  38. data: testData,
  39. expectDecryptErr: false,
  40. },
  41. "can't decrypt using incorrect key": {
  42. encryptKey: key1,
  43. decryptKey: key2,
  44. data: testData,
  45. expectDecryptErr: true,
  46. },
  47. "can't decrypt without a key": {
  48. encryptKey: key1,
  49. decryptKey: []byte{},
  50. data: testData,
  51. expectDecryptErr: true,
  52. },
  53. }
  54. for name, test := range tests {
  55. t.Run(name, func(t2 *testing.T) {
  56. encryptedData, err := EncryptBytes(test.data, test.encryptKey)
  57. if err != nil {
  58. t2.Fatalf(dedent.Dedent(
  59. "EncryptBytes failed\nerror: %v"),
  60. err,
  61. )
  62. }
  63. decryptedData, err := DecryptBytes(encryptedData, test.decryptKey)
  64. if (err != nil) != test.expectDecryptErr {
  65. t2.Fatalf(dedent.Dedent(
  66. "DecryptBytes failed\nexpected error: %t\n\tgot: %t\nerror: %v"),
  67. test.expectDecryptErr,
  68. (err != nil),
  69. err,
  70. )
  71. }
  72. if (string(decryptedData) != string(test.data)) && !test.expectDecryptErr {
  73. t2.Fatalf(dedent.Dedent(
  74. "EncryptDecryptBytes failed\nexpected decryptedData equal to data\n\tgot: data=%q decryptedData=%q"),
  75. test.data,
  76. string(decryptedData),
  77. )
  78. }
  79. })
  80. }
  81. }