github.com/linuxboot/fiano@v1.2.0/pkg/amd/manifest/checksum.go (about)

     1  // Copyright 2019 the LinuxBoot Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package manifest
     6  
     7  const (
     8  	biosDirectoryChecksumDataOffset = 8
     9  	pspDirectoryChecksumDataOffset  = 8
    10  )
    11  
    12  // CalculateBiosDirectoryCheckSum calculates expected checksum of BIOS Directory represented in serialised form
    13  func CalculateBiosDirectoryCheckSum(biosDirRaw []byte) uint32 {
    14  	return fletcherCRC32(biosDirRaw[biosDirectoryChecksumDataOffset:])
    15  }
    16  
    17  // CalculatePSPDirectoryCheckSum calculates expected checksum of PSP Directory represented in serialised form
    18  func CalculatePSPDirectoryCheckSum(pspDirRaw []byte) uint32 {
    19  	return fletcherCRC32(pspDirRaw[pspDirectoryChecksumDataOffset:])
    20  }
    21  
    22  func fletcherCRC32(data []byte) uint32 {
    23  	var c0, c1 uint32
    24  	var i int
    25  	l := (len(data) + 1) & ^1
    26  
    27  	for l > 0 {
    28  		blockLen := l
    29  		if blockLen > 360*2 {
    30  			blockLen = 360 * 2
    31  		}
    32  		l -= blockLen
    33  
    34  		for {
    35  			val := uint16(data[i])
    36  			i++
    37  			if i < len(data) {
    38  				val += uint16(data[i]) << 8
    39  				i++
    40  			}
    41  			c0 = c0 + uint32(val)
    42  			c1 = c1 + c0
    43  			blockLen -= 2
    44  			if blockLen == 0 {
    45  				break
    46  			}
    47  		}
    48  
    49  		c0 = c0 % 65535
    50  		c1 = c1 % 65535
    51  	}
    52  	return c1<<16 | c0
    53  }