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 md5 implements the MD5 hash algorithm as defined in RFC 1321.
6package md5
7
8import (
9	"crypto"
10	"hash"
11)
12
13func init() {
14	crypto.RegisterHash(crypto.MD5, New)
15}
16
17// The size of an MD5 checksum in bytes.
18const Size = 16
19
20// The blocksize of MD5 in bytes.
21const BlockSize = 64
22
23const (
24	chunk = 64
25	init0 = 0x67452301
26	init1 = 0xEFCDAB89
27	init2 = 0x98BADCFE
28	init3 = 0x10325476
29)
30
31// digest represents the partial evaluation of a checksum.
32type digest struct {
33	s   [4]uint32
34	x   [chunk]byte
35	nx  int
36	len uint64
37}
38
39func (d *digest) Reset() {
40	d.s[0] = init0
41	d.s[1] = init1
42	d.s[2] = init2
43	d.s[3] = init3
44	d.nx = 0
45	d.len = 0
46}
47
48// New returns a new hash.Hash computing the MD5 checksum.
49func New() hash.Hash {
50	d := new(digest)
51	d.Reset()
52	return d
53}
54
55func (d *digest) Size() int { return Size }
56
57func (d *digest) BlockSize() int { return BlockSize }
58
59func (d *digest) Write(p []byte) (nn int, err error) {
60	nn = len(p)
61	d.len += uint64(nn)
62	if d.nx > 0 {
63		n := len(p)
64		if n > chunk-d.nx {
65			n = chunk - d.nx
66		}
67		for i := 0; i < n; i++ {
68			d.x[d.nx+i] = p[i]
69		}
70		d.nx += n
71		if d.nx == chunk {
72			block(d, d.x[0:chunk])
73			d.nx = 0
74		}
75		p = p[n:]
76	}
77	if len(p) >= chunk {
78		n := len(p) &^ (chunk - 1)
79		block(d, p[:n])
80		p = p[n:]
81	}
82	if len(p) > 0 {
83		d.nx = copy(d.x[:], p)
84	}
85	return
86}
87
88func (d0 *digest) Sum(in []byte) []byte {
89	// Make a copy of d0 so that caller can keep writing and summing.
90	d := *d0
91
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 append(in, digest[:]...)
122}
123