crypto.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "github.com/pkg/errors"
  16. "crypto/aes"
  17. "crypto/cipher"
  18. "crypto/rand"
  19. )
  20. // CreateRandBytes returns a cryptographically secure slice of random bytes with a given size
  21. func CreateRandBytes(size uint32) ([]byte, error) {
  22. bytes := make([]byte, size)
  23. if _, err := rand.Read(bytes); err != nil {
  24. return nil, err
  25. }
  26. return bytes, nil
  27. }
  28. // EncryptBytes takes a byte slice of raw data and an encryption key and returns an encrypted byte slice of data.
  29. // The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256
  30. func EncryptBytes(data, key []byte) ([]byte, error) {
  31. block, err := aes.NewCipher(key)
  32. if err != nil {
  33. return nil, err
  34. }
  35. gcm, err := cipher.NewGCM(block)
  36. if err != nil {
  37. return nil, err
  38. }
  39. nonce, err := CreateRandBytes(uint32(gcm.NonceSize()))
  40. if err != nil {
  41. return nil, err
  42. }
  43. return gcm.Seal(nonce, nonce, data, nil), nil
  44. }
  45. // DecryptBytes takes a byte slice of encrypted data and an encryption key and returns a decrypted byte slice of data.
  46. // The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256
  47. func DecryptBytes(data, key []byte) ([]byte, error) {
  48. block, err := aes.NewCipher(key)
  49. if err != nil {
  50. return nil, err
  51. }
  52. gcm, err := cipher.NewGCM(block)
  53. if err != nil {
  54. return nil, err
  55. }
  56. nonceSize := gcm.NonceSize()
  57. if len(data) < nonceSize {
  58. return nil, errors.New("size of data is less than the nonce")
  59. }
  60. nonce, out := data[:nonceSize], data[nonceSize:]
  61. out, err = gcm.Open(nil, nonce, out, nil)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return out, nil
  66. }