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//go:generate go run gen.go -full -output md5block.go
6
7// Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
8package md5
9
10import (
11	"crypto"
12	"hash"
13)
14
15func init() {
16	crypto.RegisterHash(crypto.MD5, New)
17}
18
19// The size of an MD5 checksum in bytes.
20const Size = 16
21
22// The blocksize of MD5 in bytes.
23const BlockSize = 64
24
25const (
26	chunk = 64
27	init0 = 0x67452301
28	init1 = 0xEFCDAB89
29	init2 = 0x98BADCFE
30	init3 = 0x10325476
31)
32
33// digest represents the partial evaluation of a checksum.
34type digest struct {
35	s   [4]uint32
36	x   [chunk]byte
37	nx  int
38	len uint64
39}
40
41func (d *digest) Reset() {
42	d.s[0] = init0
43	d.s[1] = init1
44	d.s[2] = init2
45	d.s[3] = init3
46	d.nx = 0
47	d.len = 0
48}
49
50// New returns a new hash.Hash computing the MD5 checksum.
51func New() hash.Hash {
52	d := new(digest)
53	d.Reset()
54	return d
55}
56
57func (d *digest) Size() int { return Size }
58
59func (d *digest) BlockSize() int { return BlockSize }
60
61func (d *digest) Write(p []byte) (nn int, err error) {
62	nn = len(p)
63	d.len += uint64(nn)
64	if d.nx > 0 {
65		n := copy(d.x[d.nx:], p)
66		d.nx += n
67		if d.nx == chunk {
68			block(d, d.x[:])
69			d.nx = 0
70		}
71		p = p[n:]
72	}
73	if len(p) >= chunk {
74		n := len(p) &^ (chunk - 1)
75		block(d, p[:n])
76		p = p[n:]
77	}
78	if len(p) > 0 {
79		d.nx = copy(d.x[:], p)
80	}
81	return
82}
83
84func (d0 *digest) Sum(in []byte) []byte {
85	// Make a copy of d0 so that caller can keep writing and summing.
86	d := *d0
87	hash := d.checkSum()
88	return append(in, hash[:]...)
89}
90
91func (d *digest) checkSum() [Size]byte {
92	// Padding.  Add a 1 bit and 0 bits until 56 bytes mod 64.
93	len := d.len
94	var tmp [64]byte
95	tmp[0] = 0x80
96	if len%64 < 56 {
97		d.Write(tmp[0 : 56-len%64])
98	} else {
99		d.Write(tmp[0 : 64+56-len%64])
100	}
101
102	// Length in bits.
103	len <<= 3
104	for i := uint(0); i < 8; i++ {
105		tmp[i] = byte(len >> (8 * i))
106	}
107	d.Write(tmp[0:8])
108
109	if d.nx != 0 {
110		panic("d.nx != 0")
111	}
112
113	var digest [Size]byte
114	for i, s := range d.s {
115		digest[i*4] = byte(s)
116		digest[i*4+1] = byte(s >> 8)
117		digest[i*4+2] = byte(s >> 16)
118		digest[i*4+3] = byte(s >> 24)
119	}
120
121	return digest
122}
123
124// Sum returns the MD5 checksum of the data.
125func Sum(data []byte) [Size]byte {
126	var d digest
127	d.Reset()
128	d.Write(data)
129	return d.checkSum()
130}
131