Source file src/crypto/sha256/sha256.go

     1  // Copyright 2009 The Go 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 sha256 implements the SHA224 and SHA256 hash algorithms as defined
     6  // in FIPS 180-4.
     7  package sha256
     8  
     9  import (
    10  	"crypto"
    11  	"crypto/internal/boring"
    12  	_ "crypto/internal/fips/check"
    13  	"crypto/internal/fips/sha256"
    14  	"hash"
    15  )
    16  
    17  func init() {
    18  	crypto.RegisterHash(crypto.SHA224, New224)
    19  	crypto.RegisterHash(crypto.SHA256, New)
    20  }
    21  
    22  // The size of a SHA256 checksum in bytes.
    23  const Size = 32
    24  
    25  // The size of a SHA224 checksum in bytes.
    26  const Size224 = 28
    27  
    28  // The blocksize of SHA256 and SHA224 in bytes.
    29  const BlockSize = 64
    30  
    31  // New returns a new [hash.Hash] computing the SHA256 checksum. The Hash
    32  // also implements [encoding.BinaryMarshaler], [encoding.BinaryAppender] and
    33  // [encoding.BinaryUnmarshaler] to marshal and unmarshal the internal
    34  // state of the hash.
    35  func New() hash.Hash {
    36  	if boring.Enabled {
    37  		return boring.NewSHA256()
    38  	}
    39  	return sha256.New()
    40  }
    41  
    42  // New224 returns a new [hash.Hash] computing the SHA224 checksum. The Hash
    43  // also implements [encoding.BinaryMarshaler], [encoding.BinaryAppender] and
    44  // [encoding.BinaryUnmarshaler] to marshal and unmarshal the internal
    45  // state of the hash.
    46  func New224() hash.Hash {
    47  	if boring.Enabled {
    48  		return boring.NewSHA224()
    49  	}
    50  	return sha256.New224()
    51  }
    52  
    53  // Sum256 returns the SHA256 checksum of the data.
    54  func Sum256(data []byte) [Size]byte {
    55  	if boring.Enabled {
    56  		return boring.SHA256(data)
    57  	}
    58  	h := New()
    59  	h.Write(data)
    60  	var sum [Size]byte
    61  	h.Sum(sum[:0])
    62  	return sum
    63  }
    64  
    65  // Sum224 returns the SHA224 checksum of the data.
    66  func Sum224(data []byte) [Size224]byte {
    67  	if boring.Enabled {
    68  		return boring.SHA224(data)
    69  	}
    70  	h := New224()
    71  	h.Write(data)
    72  	var sum [Size224]byte
    73  	h.Sum(sum[:0])
    74  	return sum
    75  }
    76  

View as plain text