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

     1  // NXP Data Co-Processor (DCP) 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 dcp
    11  
    12  import (
    13  	"github.com/usbarmory/tamago/dma"
    14  )
    15  
    16  // SetHashDefaults initializes default values for a DCP work packet that
    17  // performs hash operation.
    18  func (pkt *WorkPacket) SetHashDefaults() {
    19  	pkt.Control0 |= 1 << DCP_CTRL0_INTERRUPT_ENABL
    20  	pkt.Control0 |= 1 << DCP_CTRL0_DECR_SEMAPHORE
    21  	pkt.Control0 |= 1 << DCP_CTRL0_ENABLE_HASH
    22  
    23  	pkt.Control1 |= HASH_SELECT_SHA256 << DCP_CTRL1_HASH_SELECT
    24  }
    25  
    26  func (hw *DCP) hash(buf []byte, mode int, size int, init bool, term bool) (sum []byte, err error) {
    27  	sourceBufferAddress := dma.Alloc(buf, 4)
    28  	defer dma.Free(sourceBufferAddress)
    29  
    30  	pkt := &WorkPacket{}
    31  	pkt.SetHashDefaults()
    32  	pkt.SourceBufferAddress = uint32(sourceBufferAddress)
    33  	pkt.BufferSize = uint32(len(buf))
    34  
    35  	if init {
    36  		pkt.Control0 |= 1 << DCP_CTRL0_HASH_INIT
    37  	}
    38  
    39  	if term {
    40  		sum = make([]byte, size)
    41  
    42  		payloadPointer := dma.Alloc(sum, 4)
    43  		defer dma.Free(payloadPointer)
    44  
    45  		pkt.Control0 |= 1 << DCP_CTRL0_HASH_TERM
    46  		pkt.PayloadPointer = uint32(payloadPointer)
    47  
    48  		defer func() {
    49  			dma.Read(payloadPointer, 0, sum)
    50  
    51  			for i, j := 0, len(sum)-1; i < j; i, j = i+1, j-1 {
    52  				sum[i], sum[j] = sum[j], sum[i]
    53  			}
    54  		}()
    55  	}
    56  
    57  	pkt.Control1 |= uint32(mode) << DCP_CTRL1_HASH_SELECT
    58  
    59  	ptr := dma.Alloc(pkt.Bytes(), 4)
    60  	defer dma.Free(ptr)
    61  
    62  	err = hw.cmd(ptr, 1)
    63  
    64  	return
    65  }