tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/lora/lorawan/mic.go (about)

     1  package lorawan
     2  
     3  import (
     4  	"encoding/binary"
     5  )
     6  
     7  // genPayloadMIC computes MIC given the payload and the key
     8  func genPayloadMIC(payload []uint8, key [16]uint8) [4]uint8 {
     9  	var mic [4]uint8
    10  	hash, _ := NewCmac(key[:])
    11  	hash.Write(payload)
    12  	hb := hash.Sum([]byte{})
    13  	copy(mic[:], hb[0:4])
    14  	return mic
    15  }
    16  
    17  func calcMessageMIC(payload []uint8, key [16]uint8, dir uint8, addr []byte, fCnt uint32, lenMessage uint8) [4]uint8 {
    18  	var b0 []byte
    19  	b0 = append(b0, 0x49, 0x00, 0x00, 0x00, 0x00)
    20  	b0 = append(b0, dir)
    21  	b0 = append(b0, addr[:]...)
    22  	var b [4]byte
    23  	binary.LittleEndian.PutUint32(b[:], fCnt)
    24  	b0 = append(b0, b[:]...)
    25  	b0 = append(b0, 0x00)
    26  	b0 = append(b0, lenMessage)
    27  
    28  	var full []byte
    29  	full = append(full, b0...)
    30  	full = append(full, payload...)
    31  
    32  	var mic [4]uint8
    33  	hash, _ := NewCmac(key[:])
    34  	hash.Write(full)
    35  	hb := hash.Sum([]byte{})
    36  	copy(mic[:], hb[0:4])
    37  	return mic
    38  }