encrypt.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2019 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package y
  17. import (
  18. "bytes"
  19. "crypto/aes"
  20. "crypto/cipher"
  21. "crypto/rand"
  22. "io"
  23. )
  24. // XORBlock encrypts the given data with AES and XOR's with IV.
  25. // Can be used for both encryption and decryption. IV is of
  26. // AES block size.
  27. func XORBlock(dst, src, key, iv []byte) error {
  28. block, err := aes.NewCipher(key)
  29. if err != nil {
  30. return err
  31. }
  32. stream := cipher.NewCTR(block, iv)
  33. stream.XORKeyStream(dst, src)
  34. return nil
  35. }
  36. func XORBlockAllocate(src, key, iv []byte) ([]byte, error) {
  37. block, err := aes.NewCipher(key)
  38. if err != nil {
  39. return nil, err
  40. }
  41. stream := cipher.NewCTR(block, iv)
  42. dst := make([]byte, len(src))
  43. stream.XORKeyStream(dst, src)
  44. return dst, nil
  45. }
  46. func XORBlockStream(w io.Writer, src, key, iv []byte) error {
  47. block, err := aes.NewCipher(key)
  48. if err != nil {
  49. return err
  50. }
  51. stream := cipher.NewCTR(block, iv)
  52. sw := cipher.StreamWriter{S: stream, W: w}
  53. _, err = io.Copy(sw, bytes.NewReader(src))
  54. return Wrapf(err, "XORBlockStream")
  55. }
  56. // GenerateIV generates IV.
  57. func GenerateIV() ([]byte, error) {
  58. iv := make([]byte, aes.BlockSize)
  59. _, err := rand.Read(iv)
  60. return iv, err
  61. }