github.com/usbarmory/tamago@v0.0.0-20240508072735-8612bbe1e454/soc/nxp/caam/cmac.go (about)

     1  // NXP Cryptographic Acceleration and Assurance Module (CAAM) driver
     2  // https://github.com/usbarmory/tamago
     3  //
     4  // Copyright (c) WithSecure Corporation
     5  // https://foundry.withsecure.com
     6  //
     7  // Use of this source code is governed by the license
     8  // that can be found in the LICENSE file.
     9  
    10  package caam
    11  
    12  import (
    13  	"crypto/aes"
    14  	"errors"
    15  
    16  	"github.com/usbarmory/tamago/dma"
    17  )
    18  
    19  func (hw *CAAM) cmac(msg []byte, key []byte, mac []byte) (err error) {
    20  	switch len(key) {
    21  	case 16, 24, 32:
    22  		break
    23  	default:
    24  		return aes.KeySizeError(len(key))
    25  	}
    26  
    27  	if len(mac) != aes.BlockSize {
    28  		return errors.New("invalid mac size")
    29  	}
    30  
    31  	keyBufferAddress := dma.Alloc(key, 4)
    32  	defer dma.Free(keyBufferAddress)
    33  
    34  	loadKey := Key{}
    35  	loadKey.SetDefaults()
    36  	loadKey.Class(1)
    37  	loadKey.Pointer(keyBufferAddress, len(key))
    38  
    39  	op := Operation{}
    40  	op.SetDefaults()
    41  	op.OpType(OPTYPE_ALG_CLASS1)
    42  	op.Algorithm(ALG_AES, AAI_AES_CMAC)
    43  	op.State(AS_INITIALIZE | AS_FINALIZE)
    44  
    45  	sourceBufferAddress := dma.Alloc(msg, 4)
    46  	defer dma.Free(sourceBufferAddress)
    47  
    48  	src := FIFOLoad{}
    49  	src.SetDefaults()
    50  	src.Class(1)
    51  	src.DataType(INPUT_DATA_TYPE_MESSAGE_DATA | INPUT_DATA_TYPE_LC1)
    52  	src.Pointer(sourceBufferAddress, len(msg))
    53  
    54  	destinationBufferAddress := dma.Alloc(mac, 4)
    55  	defer dma.Free(destinationBufferAddress)
    56  
    57  	dst := Store{}
    58  	dst.SetDefaults()
    59  	dst.Class(1)
    60  	dst.Source(CTX)
    61  	dst.Pointer(destinationBufferAddress, len(mac))
    62  
    63  	jd := loadKey.Bytes()
    64  	jd = append(jd, op.Bytes()...)
    65  	jd = append(jd, src.Bytes()...)
    66  	jd = append(jd, dst.Bytes()...)
    67  
    68  	if err = hw.job(nil, jd); err != nil {
    69  		return
    70  	}
    71  
    72  	dma.Read(destinationBufferAddress, 0, mac)
    73  
    74  	return
    75  }
    76  
    77  // SumAES returns the AES Cipher-based message authentication code (CMAC) of
    78  // the input message, the key argument should be the AES key, either 16, 24, or
    79  // 32 bytes to select AES-128, AES-192, or AES-256.
    80  //
    81  // There must be sufficient DMA memory allocated to hold the message, otherwise
    82  // the function will panic.
    83  func (hw *CAAM) SumAES(msg []byte, key []byte) (sum [16]byte, err error) {
    84  	err = hw.cmac(msg, key, sum[:])
    85  	return
    86  }