srtp.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Package srtp implements Secure Real-time Transport Protocol
  2. package srtp
  3. import (
  4. "github.com/pion/rtp"
  5. )
  6. func (c *Context) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int) ([]byte, error) {
  7. s := c.getSRTPSSRCState(header.SSRC)
  8. markAsValid, ok := s.replayDetector.Check(uint64(header.SequenceNumber))
  9. if !ok {
  10. return nil, &duplicatedError{
  11. Proto: "srtp", SSRC: header.SSRC, Index: uint32(header.SequenceNumber),
  12. }
  13. }
  14. authTagLen, err := c.cipher.rtpAuthTagLen()
  15. if err != nil {
  16. return nil, err
  17. }
  18. dst = growBufferSize(dst, len(ciphertext)-authTagLen)
  19. roc, diff := s.nextRolloverCount(header.SequenceNumber)
  20. dst, err = c.cipher.decryptRTP(dst, ciphertext, header, headerLen, roc)
  21. if err != nil {
  22. return nil, err
  23. }
  24. markAsValid()
  25. s.updateRolloverCount(header.SequenceNumber, diff)
  26. return dst, nil
  27. }
  28. // DecryptRTP decrypts a RTP packet with an encrypted payload
  29. func (c *Context) DecryptRTP(dst, encrypted []byte, header *rtp.Header) ([]byte, error) {
  30. if header == nil {
  31. header = &rtp.Header{}
  32. }
  33. headerLen, err := header.Unmarshal(encrypted)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return c.decryptRTP(dst, encrypted, header, headerLen)
  38. }
  39. // EncryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
  40. // If the dst buffer does not have the capacity to hold `len(plaintext) + 10` bytes, a new one will be allocated and returned.
  41. // If a rtp.Header is provided, it will be Unmarshaled using the plaintext.
  42. func (c *Context) EncryptRTP(dst []byte, plaintext []byte, header *rtp.Header) ([]byte, error) {
  43. if header == nil {
  44. header = &rtp.Header{}
  45. }
  46. headerLen, err := header.Unmarshal(plaintext)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return c.encryptRTP(dst, header, plaintext[headerLen:])
  51. }
  52. // encryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
  53. // If the dst buffer does not have the capacity, a new one will be allocated and returned.
  54. // Similar to above but faster because it can avoid unmarshaling the header and marshaling the payload.
  55. func (c *Context) encryptRTP(dst []byte, header *rtp.Header, payload []byte) (ciphertext []byte, err error) {
  56. s := c.getSRTPSSRCState(header.SSRC)
  57. roc, diff := s.nextRolloverCount(header.SequenceNumber)
  58. s.updateRolloverCount(header.SequenceNumber, diff)
  59. return c.cipher.encryptRTP(dst, header, payload, roc)
  60. }