crypto.go 903 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package srtp
  4. import (
  5. "crypto/cipher"
  6. "github.com/pion/transport/v2/utils/xor"
  7. )
  8. // incrementCTR increments a big-endian integer of arbitrary size.
  9. func incrementCTR(ctr []byte) {
  10. for i := len(ctr) - 1; i >= 0; i-- {
  11. ctr[i]++
  12. if ctr[i] != 0 {
  13. break
  14. }
  15. }
  16. }
  17. // xorBytesCTR performs CTR encryption and decryption.
  18. // It is equivalent to cipher.NewCTR followed by XORKeyStream.
  19. func xorBytesCTR(block cipher.Block, iv []byte, dst, src []byte) error {
  20. if len(iv) != block.BlockSize() {
  21. return errBadIVLength
  22. }
  23. ctr := make([]byte, len(iv))
  24. copy(ctr, iv)
  25. bs := block.BlockSize()
  26. stream := make([]byte, bs)
  27. i := 0
  28. for i < len(src) {
  29. block.Encrypt(stream, ctr)
  30. incrementCTR(ctr)
  31. n := xor.XorBytes(dst[i:], src[i:], stream)
  32. if n == 0 {
  33. break
  34. }
  35. i += n
  36. }
  37. return nil
  38. }