2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
12 #include "internal/cryptlib.h"
13 #include <openssl/buffer.h>
14 #include <openssl/evp.h>
15 #include "internal/evp_int.h"
17 #include "internal/bio.h"
20 * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest
23 static int md_write(BIO *h, char const *buf, int num);
24 static int md_read(BIO *h, char *buf, int size);
26 * static int md_puts(BIO *h, const char *str);
28 static int md_gets(BIO *h, char *str, int size);
29 static long md_ctrl(BIO *h, int cmd, long arg1, void *arg2);
30 static int md_new(BIO *h);
31 static int md_free(BIO *data);
32 static long md_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
34 static const BIO_METHOD methods_md = {
35 BIO_TYPE_MD, "message digest",
36 /* TODO: Convert to new style write function */
39 /* TODO: Convert to new style read function */
50 const BIO_METHOD *BIO_f_md(void)
55 static int md_new(BIO *bi)
59 ctx = EVP_MD_CTX_new();
64 BIO_set_data(bi, ctx);
69 static int md_free(BIO *a)
73 EVP_MD_CTX_free(BIO_get_data(a));
74 BIO_set_data(a, NULL);
80 static int md_read(BIO *b, char *out, int outl)
89 ctx = BIO_get_data(b);
92 if ((ctx == NULL) || (next == NULL))
95 ret = BIO_read(next, out, outl);
96 if (BIO_get_init(b)) {
98 if (EVP_DigestUpdate(ctx, (unsigned char *)out,
99 (unsigned int)ret) <= 0)
103 BIO_clear_retry_flags(b);
104 BIO_copy_next_retry(b);
108 static int md_write(BIO *b, const char *in, int inl)
114 if ((in == NULL) || (inl <= 0))
117 ctx = BIO_get_data(b);
119 if ((ctx != NULL) && (next != NULL))
120 ret = BIO_write(next, in, inl);
122 if (BIO_get_init(b)) {
124 if (!EVP_DigestUpdate(ctx, (const unsigned char *)in,
125 (unsigned int)ret)) {
126 BIO_clear_retry_flags(b);
132 BIO_clear_retry_flags(b);
133 BIO_copy_next_retry(b);
138 static long md_ctrl(BIO *b, int cmd, long num, void *ptr)
140 EVP_MD_CTX *ctx, *dctx, **pctx;
147 ctx = BIO_get_data(b);
153 ret = EVP_DigestInit_ex(ctx, ctx->digest, NULL);
157 ret = BIO_ctrl(next, cmd, num, ptr);
160 if (BIO_get_init(b)) {
166 case BIO_C_GET_MD_CTX:
171 case BIO_C_SET_MD_CTX:
173 BIO_set_data(b, ptr);
177 case BIO_C_DO_STATE_MACHINE:
178 BIO_clear_retry_flags(b);
179 ret = BIO_ctrl(next, cmd, num, ptr);
180 BIO_copy_next_retry(b);
185 ret = EVP_DigestInit_ex(ctx, md, NULL);
191 dctx = BIO_get_data(dbio);
192 if (!EVP_MD_CTX_copy_ex(dctx, ctx))
197 ret = BIO_ctrl(next, cmd, num, ptr);
203 static long md_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
215 ret = BIO_callback_ctrl(next, cmd, fp);
221 static int md_gets(BIO *bp, char *buf, int size)
226 ctx = BIO_get_data(bp);
228 if (size < ctx->digest->md_size)
231 if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0)