File: sha1.go

package info (click to toggle)
golang-github-mmcloughlin-avo 0.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 15,024 kB
  • sloc: xml: 71,029; asm: 14,862; sh: 194; makefile: 21; ansic: 11
file content (44 lines) | stat: -rw-r--r-- 841 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package sha1

import "encoding/binary"

// Size of a SHA-1 checksum in bytes.
const Size = 20

// BlockSize is the block size of SHA-1 in bytes.
const BlockSize = 64

// Sum returns the SHA-1 checksum of data.
func Sum(data []byte) [Size]byte {
	n := len(data)
	h := [5]uint32{0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0}

	// Consume full blocks.
	for len(data) >= BlockSize {
		block(&h, data)
		data = data[BlockSize:]
	}

	// Final block.
	tmp := make([]byte, BlockSize)
	copy(tmp, data)
	tmp[len(data)] = 0x80

	if len(data) >= 56 {
		block(&h, tmp)
		for i := 0; i < BlockSize; i++ {
			tmp[i] = 0
		}
	}

	binary.BigEndian.PutUint64(tmp[56:], uint64(8*n))
	block(&h, tmp)

	// Write into byte array.
	var digest [Size]byte
	for i := 0; i < 5; i++ {
		binary.BigEndian.PutUint32(digest[4*i:], h[i])
	}

	return digest
}