Revert "Merge branch 'upstream' into tizen"
[platform/upstream/nettle.git] / md5.c
1 /* md5.c
2  *
3  * The MD5 hash function, described in RFC 1321.
4  */
5
6 /* nettle, low-level cryptographics library
7  *
8  * Copyright (C) 2001 Niels Möller
9  *  
10  * The nettle library is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or (at your
13  * option) any later version.
14  * 
15  * The nettle library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18  * License for more details.
19  * 
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with the nettle library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23  * MA 02111-1301, USA.
24  */
25
26 /* Based on public domain code hacked by Colin Plumb, Andrew Kuchling, and
27  * Niels Möller. */
28
29 #if HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <assert.h>
34 #include <string.h>
35
36 #include "md5.h"
37
38 #include "macros.h"
39 #include "nettle-write.h"
40
41 void
42 md5_init(struct md5_ctx *ctx)
43 {
44   const uint32_t iv[_MD5_DIGEST_LENGTH] =
45     {
46       0x67452301,
47       0xefcdab89,
48       0x98badcfe,
49       0x10325476,
50     };
51   memcpy(ctx->state, iv, sizeof(ctx->state));
52   ctx->count_low = ctx->count_high = 0;
53   ctx->index = 0;
54 }
55
56 #define COMPRESS(ctx, data) (_nettle_md5_compress((ctx)->state, (data)))
57
58 void
59 md5_update(struct md5_ctx *ctx,
60            unsigned length,
61            const uint8_t *data)
62 {
63   MD_UPDATE(ctx, length, data, COMPRESS, MD_INCR(ctx));
64 }
65
66 void
67 md5_digest(struct md5_ctx *ctx,
68            unsigned length,
69            uint8_t *digest)
70 {
71   uint32_t high, low;
72   
73   assert(length <= MD5_DIGEST_SIZE);
74
75   MD_PAD(ctx, 8, COMPRESS);
76
77   /* There are 512 = 2^9 bits in one block */  
78   high = (ctx->count_high << 9) | (ctx->count_low >> 23);
79   low = (ctx->count_low << 9) | (ctx->index << 3);
80
81   LE_WRITE_UINT32(ctx->block + (MD5_DATA_SIZE - 8), low);
82   LE_WRITE_UINT32(ctx->block + (MD5_DATA_SIZE - 4), high);
83   _nettle_md5_compress(ctx->state, ctx->block);
84
85   _nettle_write_le32(length, digest, ctx->state);
86   md5_init(ctx);
87 }