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