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);
25 static int md_gets(BIO *h, char *str, int size);
26 static long md_ctrl(BIO *h, int cmd, long arg1, void *arg2);
27 static int md_new(BIO *h);
28 static int md_free(BIO *data);
29 static long md_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
31 static const BIO_METHOD methods_md = {
32 BIO_TYPE_MD, "message digest",
33 /* TODO: Convert to new style write function */
36 /* TODO: Convert to new style read function */
47 const BIO_METHOD *BIO_f_md(void)
52 static int md_new(BIO *bi)
56 ctx = EVP_MD_CTX_new();
61 BIO_set_data(bi, ctx);
66 static int md_free(BIO *a)
70 EVP_MD_CTX_free(BIO_get_data(a));
71 BIO_set_data(a, NULL);
77 static int md_read(BIO *b, char *out, int outl)
86 ctx = BIO_get_data(b);
89 if ((ctx == NULL) || (next == NULL))
92 ret = BIO_read(next, out, outl);
93 if (BIO_get_init(b)) {
95 if (EVP_DigestUpdate(ctx, (unsigned char *)out,
96 (unsigned int)ret) <= 0)
100 BIO_clear_retry_flags(b);
101 BIO_copy_next_retry(b);
105 static int md_write(BIO *b, const char *in, int inl)
111 if ((in == NULL) || (inl <= 0))
114 ctx = BIO_get_data(b);
116 if ((ctx != NULL) && (next != NULL))
117 ret = BIO_write(next, in, inl);
119 if (BIO_get_init(b)) {
121 if (!EVP_DigestUpdate(ctx, (const unsigned char *)in,
122 (unsigned int)ret)) {
123 BIO_clear_retry_flags(b);
129 BIO_clear_retry_flags(b);
130 BIO_copy_next_retry(b);
135 static long md_ctrl(BIO *b, int cmd, long num, void *ptr)
137 EVP_MD_CTX *ctx, *dctx, **pctx;
144 ctx = BIO_get_data(b);
150 ret = EVP_DigestInit_ex(ctx, ctx->digest, NULL);
154 ret = BIO_ctrl(next, cmd, num, ptr);
157 if (BIO_get_init(b)) {
163 case BIO_C_GET_MD_CTX:
168 case BIO_C_SET_MD_CTX:
170 BIO_set_data(b, ptr);
174 case BIO_C_DO_STATE_MACHINE:
175 BIO_clear_retry_flags(b);
176 ret = BIO_ctrl(next, cmd, num, ptr);
177 BIO_copy_next_retry(b);
182 ret = EVP_DigestInit_ex(ctx, md, NULL);
188 dctx = BIO_get_data(dbio);
189 if (!EVP_MD_CTX_copy_ex(dctx, ctx))
194 ret = BIO_ctrl(next, cmd, num, ptr);
200 static long md_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
212 ret = BIO_callback_ctrl(next, cmd, fp);
218 static int md_gets(BIO *bp, char *buf, int size)
223 ctx = BIO_get_data(bp);
225 if (size < ctx->digest->md_size)
228 if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0)