github.com/f-secure-foundry/tamago@v0.0.0-20220307101044-d73fcdd7f11b/soc/imx6/dcp/hash.go (about)

     1  // NXP Data Co-Processor (DCP) driver
     2  // https://github.com/f-secure-foundry/tamago
     3  //
     4  // Copyright (c) F-Secure Corporation
     5  // https://foundry.f-secure.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/f-secure-foundry/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 hash(buf []byte, mode uint32, init bool, term bool) (sum []byte, err error) {
    27  	pkt := &WorkPacket{}
    28  	pkt.SetHashDefaults()
    29  
    30  	pkt.BufferSize = uint32(len(buf))
    31  
    32  	pkt.SourceBufferAddress = dma.Alloc(buf, 4)
    33  	defer dma.Free(pkt.SourceBufferAddress)
    34  
    35  	if init {
    36  		pkt.Control0 |= 1 << DCP_CTRL0_HASH_INIT
    37  	}
    38  
    39  	if term {
    40  		// output is always 32 bytes, regardless of mode
    41  		sum = make([]byte, 32)
    42  
    43  		pkt.PayloadPointer = dma.Alloc(sum, 4)
    44  		defer dma.Free(pkt.PayloadPointer)
    45  
    46  		pkt.Control0 |= 1 << DCP_CTRL0_HASH_TERM
    47  	}
    48  
    49  	pkt.Control1 |= mode << DCP_CTRL1_HASH_SELECT
    50  
    51  	ptr := dma.Alloc(pkt.Bytes(), 4)
    52  	defer dma.Free(ptr)
    53  
    54  	err = cmd(ptr, 1)
    55  
    56  	if err != nil {
    57  		return
    58  	}
    59  
    60  	dma.Read(pkt.PayloadPointer, 0, sum)
    61  
    62  	for i, j := 0, len(sum)-1; i < j; i, j = i+1, j-1 {
    63  		sum[i], sum[j] = sum[j], sum[i]
    64  	}
    65  
    66  	return
    67  }