xref: /plan9/sys/src/cmd/gs/src/smd5.c (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
1 /* Copyright (C) 2000 Aladdin Enterprises.  All rights reserved.
2 
3   This software is provided AS-IS with no warranty, either express or
4   implied.
5 
6   This software is distributed under license and may not be copied,
7   modified or distributed except as expressly authorized under the terms
8   of the license contained in the file LICENSE in this distribution.
9 
10   For more information about licensing, please refer to
11   http://www.ghostscript.com/licensing/. For information on
12   commercial licensing, go to http://www.artifex.com/licensing/ or
13   contact Artifex Software, Inc., 101 Lucas Valley Road #110,
14   San Rafael, CA  94903, U.S.A., +1(415)492-9861.
15 */
16 
17 /* $Id: smd5.c,v 1.6 2004/01/13 14:03:30 igor Exp $ */
18 /* MD5Encode filter */
19 #include "memory_.h"
20 #include "strimpl.h"
21 #include "stream.h"
22 #include "smd5.h"
23 
24 /* ------ MD5Encode ------ */
25 
26 private_st_MD5E_state();
27 
28 /* Initialize the state. */
29 private int
s_MD5E_init(stream_state * st)30 s_MD5E_init(stream_state * st)
31 {
32     stream_MD5E_state *const ss = (stream_MD5E_state *) st;
33 
34     md5_init(&ss->md5);
35     return 0;
36 }
37 
38 /* Process a buffer. */
39 private int
s_MD5E_process(stream_state * st,stream_cursor_read * pr,stream_cursor_write * pw,bool last)40 s_MD5E_process(stream_state * st, stream_cursor_read * pr,
41 	       stream_cursor_write * pw, bool last)
42 {
43     stream_MD5E_state *const ss = (stream_MD5E_state *) st;
44     int status = 0;
45 
46     if (pr->ptr < pr->limit) {
47 	md5_append(&ss->md5, pr->ptr + 1, pr->limit - pr->ptr);
48 	pr->ptr = pr->limit;
49     }
50     if (last) {
51 	if (pw->limit - pw->ptr >= 16) {
52 	    md5_finish(&ss->md5, pw->ptr + 1);
53 	    pw->ptr += 16;
54 	    status = EOFC;
55 	} else
56 	    status = 1;
57     }
58     return status;
59 }
60 
61 /* Stream template */
62 const stream_template s_MD5E_template = {
63     &st_MD5E_state, s_MD5E_init, s_MD5E_process, 1, 16
64 };
65 
66 stream *
s_MD5E_make_stream(gs_memory_t * mem,byte * digest,int digest_size)67 s_MD5E_make_stream(gs_memory_t *mem, byte *digest, int digest_size)
68 {
69     stream *s = s_alloc(mem, "s_MD5E_make_stream");
70     stream_state *ss = s_alloc_state(mem, s_MD5E_template.stype, "s_MD5E_make_stream");
71 
72     if (ss == NULL || s == NULL)
73 	goto err;
74     ss->template = &s_MD5E_template;
75     if (s_init_filter(s, ss, digest, digest_size, NULL) < 0)
76 	goto err;
77     s->strm = s;
78     return s;
79 err:
80     gs_free_object(mem, ss, "s_MD5E_make_stream");
81     gs_free_object(mem, s, "s_MD5E_make_stream");
82     return NULL;
83 }
84