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",
46 const BIO_METHOD *BIO_f_md(void)
51 static int md_new(BIO *bi)
55 ctx = EVP_MD_CTX_new();
60 BIO_set_data(bi, ctx);
65 static int md_free(BIO *a)
69 EVP_MD_CTX_free(BIO_get_data(a));
70 BIO_set_data(a, NULL);
76 static int md_read(BIO *b, char *out, int outl)
85 ctx = BIO_get_data(b);
88 if ((ctx == NULL) || (next == NULL))
91 ret = BIO_read(next, out, outl);
92 if (BIO_get_init(b)) {
94 if (EVP_DigestUpdate(ctx, (unsigned char *)out,
95 (unsigned int)ret) <= 0)
99 BIO_clear_retry_flags(b);
100 BIO_copy_next_retry(b);
104 static int md_write(BIO *b, const char *in, int inl)
110 if ((in == NULL) || (inl <= 0))
113 ctx = BIO_get_data(b);
115 if ((ctx != NULL) && (next != NULL))
116 ret = BIO_write(next, in, inl);
118 if (BIO_get_init(b)) {
120 if (!EVP_DigestUpdate(ctx, (const unsigned char *)in,
121 (unsigned int)ret)) {
122 BIO_clear_retry_flags(b);
128 BIO_clear_retry_flags(b);
129 BIO_copy_next_retry(b);
134 static long md_ctrl(BIO *b, int cmd, long num, void *ptr)
136 EVP_MD_CTX *ctx, *dctx, **pctx;
143 ctx = BIO_get_data(b);
149 ret = EVP_DigestInit_ex(ctx, ctx->digest, NULL);
153 ret = BIO_ctrl(next, cmd, num, ptr);
156 if (BIO_get_init(b)) {
162 case BIO_C_GET_MD_CTX:
167 case BIO_C_SET_MD_CTX:
169 BIO_set_data(b, ptr);
173 case BIO_C_DO_STATE_MACHINE:
174 BIO_clear_retry_flags(b);
175 ret = BIO_ctrl(next, cmd, num, ptr);
176 BIO_copy_next_retry(b);
181 ret = EVP_DigestInit_ex(ctx, md, NULL);
187 dctx = BIO_get_data(dbio);
188 if (!EVP_MD_CTX_copy_ex(dctx, ctx))
193 ret = BIO_ctrl(next, cmd, num, ptr);
199 static long md_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
211 ret = BIO_callback_ctrl(next, cmd, fp);
217 static int md_gets(BIO *bp, char *buf, int size)
222 ctx = BIO_get_data(bp);
224 if (size < ctx->digest->md_size)
227 if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0)