2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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 <openssl/buffer.h>
13 #include <openssl/evp.h>
14 #include "internal/bio.h"
17 * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest
20 static int md_write(BIO *h, char const *buf, int num);
21 static int md_read(BIO *h, char *buf, int size);
22 static int md_gets(BIO *h, char *str, int size);
23 static long md_ctrl(BIO *h, int cmd, long arg1, void *arg2);
24 static int md_new(BIO *h);
25 static int md_free(BIO *data);
26 static long md_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp);
28 static const BIO_METHOD methods_md = {
43 const BIO_METHOD *BIO_f_md(void)
48 static int md_new(BIO *bi)
52 ctx = EVP_MD_CTX_new();
57 BIO_set_data(bi, ctx);
62 static int md_free(BIO *a)
66 EVP_MD_CTX_free(BIO_get_data(a));
67 BIO_set_data(a, NULL);
73 static int md_read(BIO *b, char *out, int outl)
82 ctx = BIO_get_data(b);
85 if ((ctx == NULL) || (next == NULL))
88 ret = BIO_read(next, out, outl);
89 if (BIO_get_init(b)) {
91 if (EVP_DigestUpdate(ctx, (unsigned char *)out,
92 (unsigned int)ret) <= 0)
96 BIO_clear_retry_flags(b);
97 BIO_copy_next_retry(b);
101 static int md_write(BIO *b, const char *in, int inl)
107 if ((in == NULL) || (inl <= 0))
110 ctx = BIO_get_data(b);
112 if ((ctx != NULL) && (next != NULL))
113 ret = BIO_write(next, in, inl);
115 if (BIO_get_init(b)) {
117 if (!EVP_DigestUpdate(ctx, (const unsigned char *)in,
118 (unsigned int)ret)) {
119 BIO_clear_retry_flags(b);
125 BIO_clear_retry_flags(b);
126 BIO_copy_next_retry(b);
131 static long md_ctrl(BIO *b, int cmd, long num, void *ptr)
133 EVP_MD_CTX *ctx, *dctx, **pctx;
140 ctx = BIO_get_data(b);
146 ret = EVP_DigestInit_ex(ctx, EVP_MD_CTX_get0_md(ctx), NULL);
150 ret = BIO_ctrl(next, cmd, num, ptr);
153 if (BIO_get_init(b)) {
155 *ppmd = EVP_MD_CTX_get0_md(ctx);
159 case BIO_C_GET_MD_CTX:
164 case BIO_C_SET_MD_CTX:
166 BIO_set_data(b, ptr);
170 case BIO_C_DO_STATE_MACHINE:
171 BIO_clear_retry_flags(b);
172 ret = BIO_ctrl(next, cmd, num, ptr);
173 BIO_copy_next_retry(b);
178 ret = EVP_DigestInit_ex(ctx, md, NULL);
184 dctx = BIO_get_data(dbio);
185 if (!EVP_MD_CTX_copy_ex(dctx, ctx))
190 ret = BIO_ctrl(next, cmd, num, ptr);
196 static long md_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
205 return BIO_callback_ctrl(next, cmd, fp);
208 static int md_gets(BIO *bp, char *buf, int size)
213 ctx = BIO_get_data(bp);
215 if (size < EVP_MD_CTX_get_size(ctx))
218 if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0)