Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

sha1.gno

6.84 Kb · 277 lines
  1// Package sha1 implements SHA-1 (FIPS 180-1, RFC 3174) as a pure, reusable
  2// package: one-shot, streaming, HMAC-SHA1, and git object ids.
  3//
  4// SHA-1 compresses the message 64 bytes at a time into five 32-bit words,
  5// through 80 rounds that rotate, add and mix a round constant chosen per
  6// quarter. The whole algorithm is those 80 rounds plus a padding rule: a single
  7// 0x80 byte, zeros up to 56 bytes mod 64, then the message length in bits as a
  8// big-endian uint64. Almost every bug in a hand-written SHA-1 is in that
  9// padding rule, which is why the tests walk every length across the boundary.
 10//
 11// SHA-1 is BROKEN as a collision-resistant hash: SHAttered (2017) produced two
 12// different PDFs with the same digest, and a chosen-prefix collision followed in
 13// 2020. Never use it to decide that two documents are the same document, and
 14// never use it for a new signature scheme. It is still correct, and still the
 15// only answer, where an external format specifies it: git object ids, HMAC-SHA1
 16// in TOTP and older AWS signatures, and legacy checksum interop.
 17//
 18// A live demo of this package is at
 19// [r/moul/x/daily/sha1demo](/r/moul/x/daily/sha1demo/v0).
 20package sha1
 21
 22import "strings"
 23
 24// Size is the length of a SHA-1 digest in bytes.
 25const Size = 20
 26
 27// BlockSize is SHA-1's block size in bytes. HMAC's key padding depends on it.
 28const BlockSize = 64
 29
 30// The five initialization constants, FIPS 180-1 section 5.
 31const (
 32	init0 = 0x67452301
 33	init1 = 0xEFCDAB89
 34	init2 = 0x98BADCFE
 35	init3 = 0x10325476
 36	init4 = 0xC3D2E1F0
 37)
 38
 39// The four round constants, one per 20 rounds.
 40const (
 41	k0 = 0x5A827999
 42	k1 = 0x6ED9EBA1
 43	k2 = 0x8F1BBCDC
 44	k3 = 0xCA62C1D6
 45)
 46
 47// Digest is a streaming SHA-1 state: feed it with Write, read it with Sum.
 48//
 49// Sum is NOT destructive. It finalizes a copy, so a Digest can be read and then
 50// written to again, and reading it twice gives the same answer.
 51type Digest struct {
 52	h   [5]uint32
 53	buf [BlockSize]byte
 54	n   int    // bytes currently in buf
 55	len uint64 // total bytes written
 56}
 57
 58// New returns a Digest ready to hash a fresh message.
 59func New() *Digest {
 60	d := &Digest{}
 61	d.Reset()
 62	return d
 63}
 64
 65// Reset restarts the digest as if nothing had been written.
 66func (d *Digest) Reset() {
 67	d.h = [5]uint32{init0, init1, init2, init3, init4}
 68	d.n = 0
 69	d.len = 0
 70}
 71
 72// Write adds s to the message. Any number of calls is equivalent to one call
 73// with the concatenation.
 74func (d *Digest) Write(s string) {
 75	d.len += uint64(len(s))
 76	i := 0
 77	// Top up the partial block first.
 78	if d.n > 0 {
 79		for i < len(s) && d.n < BlockSize {
 80			d.buf[d.n] = s[i]
 81			d.n++
 82			i++
 83		}
 84		if d.n == BlockSize {
 85			d.block(d.buf[:])
 86			d.n = 0
 87		}
 88	}
 89	// Then consume whole blocks straight out of s.
 90	for i+BlockSize <= len(s) {
 91		var b [BlockSize]byte
 92		for j := 0; j < BlockSize; j++ {
 93			b[j] = s[i+j]
 94		}
 95		d.block(b[:])
 96		i += BlockSize
 97	}
 98	// Whatever is left is the new partial block.
 99	for i < len(s) {
100		d.buf[d.n] = s[i]
101		d.n++
102		i++
103	}
104}
105
106// Sum returns the digest of everything written so far, without finalizing the
107// receiver: padding is applied to a copy.
108func (d *Digest) Sum() [Size]byte {
109	c := *d
110	bits := c.len * 8
111
112	// 0x80, then zeros until 56 bytes mod 64, then the bit length.
113	var pad [BlockSize * 2]byte
114	pad[0] = 0x80
115	padLen := 56 - int(c.len%BlockSize)
116	if padLen <= 0 {
117		padLen += BlockSize
118	}
119	for i := 0; i < 8; i++ {
120		pad[padLen+i] = byte(bits >> uint(56-8*i))
121	}
122	c.writePadding(pad[:padLen+8])
123
124	var out [Size]byte
125	for i := 0; i < 5; i++ {
126		out[4*i] = byte(c.h[i] >> 24)
127		out[4*i+1] = byte(c.h[i] >> 16)
128		out[4*i+2] = byte(c.h[i] >> 8)
129		out[4*i+3] = byte(c.h[i])
130	}
131	return out
132}
133
134// writePadding feeds the final padding block. It deliberately does NOT count
135// the bytes into d.len: the length field is already encoded in what it writes.
136func (d *Digest) writePadding(p []byte) {
137	for _, b := range p {
138		d.buf[d.n] = b
139		d.n++
140		if d.n == BlockSize {
141			d.block(d.buf[:])
142			d.n = 0
143		}
144	}
145}
146
147// block runs the 80 rounds over one 64-byte block.
148func (d *Digest) block(p []byte) {
149	var w [80]uint32
150	for i := 0; i < 16; i++ {
151		w[i] = uint32(p[4*i])<<24 | uint32(p[4*i+1])<<16 | uint32(p[4*i+2])<<8 | uint32(p[4*i+3])
152	}
153	// The message schedule: this one-bit rotate is the only difference
154	// between SHA-1 and the withdrawn SHA-0.
155	for i := 16; i < 80; i++ {
156		x := w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]
157		w[i] = x<<1 | x>>31
158	}
159
160	a, b, c, e5 := d.h[0], d.h[1], d.h[2], d.h[3]
161	e := d.h[4]
162	for i := 0; i < 80; i++ {
163		var f, k uint32
164		switch {
165		case i < 20:
166			f, k = (b&c)|(^b&e5), k0
167		case i < 40:
168			f, k = b^c^e5, k1
169		case i < 60:
170			f, k = (b&c)|(b&e5)|(c&e5), k2
171		default:
172			f, k = b^c^e5, k3
173		}
174		t := (a<<5 | a>>27) + f + e + k + w[i]
175		e = e5
176		e5 = c
177		c = b<<30 | b>>2
178		b = a
179		a = t
180	}
181	d.h[0] += a
182	d.h[1] += b
183	d.h[2] += c
184	d.h[3] += e5
185	d.h[4] += e
186}
187
188// Sum returns the SHA-1 digest of s.
189func Sum(s string) [Size]byte {
190	d := New()
191	d.Write(s)
192	return d.Sum()
193}
194
195// SumHex returns the SHA-1 digest of s as 40 lowercase hex digits.
196func SumHex(s string) string { return Hex(Sum(s)) }
197
198// Hex renders a digest as 40 lowercase hex digits.
199func Hex(sum [Size]byte) string {
200	const digits = "0123456789abcdef"
201	var b strings.Builder
202	for _, c := range sum {
203		b.WriteByte(digits[c>>4])
204		b.WriteByte(digits[c&0x0F])
205	}
206	return b.String()
207}
208
209// Verify reports whether s hashes to hexDigest, which may be in either case.
210//
211// This is an equality check on a digest, not an authentication primitive: see
212// the package doc on why SHA-1 must not decide that two documents match.
213func Verify(s, hexDigest string) bool {
214	return SumHex(s) == strings.ToLower(strings.TrimSpace(hexDigest))
215}
216
217// HMAC returns the HMAC-SHA1 of msg under key (RFC 2104).
218//
219// A key longer than BlockSize is hashed down to 20 bytes first, which is why
220// an 80-byte key and the SHA-1 of that key are the same key.
221func HMAC(key, msg string) [Size]byte {
222	var k [BlockSize]byte
223	if len(key) > BlockSize {
224		sum := Sum(key)
225		for i := 0; i < Size; i++ {
226			k[i] = sum[i]
227		}
228	} else {
229		for i := 0; i < len(key); i++ {
230			k[i] = key[i]
231		}
232	}
233
234	var ipad, opad [BlockSize]byte
235	for i := 0; i < BlockSize; i++ {
236		ipad[i] = k[i] ^ 0x36
237		opad[i] = k[i] ^ 0x5C
238	}
239
240	inner := New()
241	inner.Write(string(ipad[:]))
242	inner.Write(msg)
243	is := inner.Sum()
244
245	outer := New()
246	outer.Write(string(opad[:]))
247	outer.Write(string(is[:]))
248	return outer.Sum()
249}
250
251// HMACHex returns the HMAC-SHA1 of msg under key as lowercase hex.
252func HMACHex(key, msg string) string { return Hex(HMAC(key, msg)) }
253
254// GitBlobID returns the git object id of content: SHA-1 over the header
255// "blob <len>\x00" followed by the bytes. It matches `git hash-object`.
256func GitBlobID(content string) string {
257	d := New()
258	d.Write("blob ")
259	d.Write(itoa(len(content)))
260	d.Write("\x00")
261	d.Write(content)
262	return Hex(d.Sum())
263}
264
265func itoa(n int) string {
266	if n == 0 {
267		return "0"
268	}
269	var b [20]byte
270	i := len(b)
271	for n > 0 {
272		i--
273		b[i] = byte('0' + n%10)
274		n /= 10
275	}
276	return string(b[i:])
277}