// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package srtp

import (
	
	
)

func aesCmKeyDerivation( byte, ,  []byte,  int,  int) ([]byte, error) {
	if  != 0 {
		// 24-bit "index DIV kdr" must be xored to prf input.
		return nil, errNonZeroKDRNotSupported
	}

	// https://tools.ietf.org/html/rfc3711#appendix-B.3
	// The input block for AES-CM is generated by exclusive-oring the master salt with the
	// concatenation of the encryption key label 0x00 with (index DIV kdr),
	// - index is 'rollover count' and DIV is 'divided by'

	 := len()

	 := make([]byte, 16)
	copy([:], )

	[7] ^= 

	// The resulting value is then AES encrypted using the master key to get the cipher key.
	,  := aes.NewCipher()
	if  != nil {
		return nil, 
	}

	 := .BlockSize()
	 := make([]byte, ((+-1)/)*)
	var  uint16
	for  := 0;  < ;  +=  {
		binary.BigEndian.PutUint16([len()-2:], )
		.Encrypt([:+], )
		++
	}

	return [:], nil
}

// Generate IV https://tools.ietf.org/html/rfc3711#section-4.1.1
// where the 128-bit integer value IV SHALL be defined by the SSRC, the
// SRTP packet index i, and the SRTP session salting key k_s, as below.
// - ROC = a 32-bit unsigned rollover counter (ROC), which records how many
// -       times the 16-bit RTP sequence number has been reset to zero after
// -       passing through 65,535
// i = 2^16 * ROC + SEQ
// IV = (salt*2 ^ 16) | (ssrc*2 ^ 64) | (i*2 ^ 16).
func generateCounter(
	 uint16,
	 uint32,
	 uint32,  []byte,
) ( [16]byte) {
	copy([:], )

	[4] ^= byte( >> 24)
	[5] ^= byte( >> 16)
	[6] ^= byte( >> 8)
	[7] ^= byte()
	[8] ^= byte( >> 24)
	[9] ^= byte( >> 16)
	[10] ^= byte( >> 8)
	[11] ^= byte()
	[12] ^= byte( >> 8)
	[13] ^= byte()

	return 
}