github.com/tunabay/go-bitarray@v1.3.1/bitarray_sha1.go (about)

     1  // Copyright (c) 2021 Hirotsuna Mizuno. All rights reserved.
     2  // Use of this source code is governed by the MIT license that can be found in
     3  // the LICENSE file.
     4  
     5  package bitarray
     6  
     7  import (
     8  	//nolint:gosec // intentionally provided option
     9  	_ "crypto/sha1" // block()
    10  	"encoding/binary"
    11  	_ "unsafe" // linkname
    12  )
    13  
    14  // SHA1 returns the SHA-1 checksum of the bit array. It treats the bit array as
    15  // a bit-oriented message to compute the checksum as defined in RFC 3174.
    16  func (ba *BitArray) SHA1() [20]byte {
    17  	nBits := ba.Len()
    18  	buf := NewBuffer((nBits + 1 + 64 + 511) &^ 511)
    19  	buf.PutBitArrayAt(0, ba)
    20  	buf.PutBitAt(nBits, 1)
    21  	binary.BigEndian.PutUint64(buf.b[len(buf.b)-8:], uint64(nBits))
    22  
    23  	d := &sha1Digest{}
    24  	sha1Reset(d)
    25  	sha1Block(d, buf.b)
    26  
    27  	var sha1 [20]byte
    28  	for i := 0; i < 5; i++ {
    29  		binary.BigEndian.PutUint32(sha1[i<<2:], d.h[i])
    30  	}
    31  
    32  	return sha1
    33  }
    34  
    35  // crypto/sha1.digest
    36  // TODO: if possible, use crypto/sha1.digest directly
    37  type sha1Digest struct {
    38  	h   [5]uint32
    39  	x   [64]byte //nolint:structcheck,unused // for Reset()
    40  	nx  int      //nolint:structcheck,unused // for Reset()
    41  	len uint64   //nolint:structcheck,unused // for Reset()
    42  }
    43  
    44  //go:linkname sha1Block crypto/sha1.block
    45  func sha1Block(*sha1Digest, []byte)
    46  
    47  //go:linkname sha1Reset crypto/sha1.(*digest).Reset
    48  func sha1Reset(*sha1Digest)