1#include <libkern/crypto/crypto_internal.h>
2#include <libkern/crypto/md5.h>
3#include <kern/debug.h>
4#include <corecrypto/ccdigest.h>
5
6static uint64_t
7getCount(MD5_CTX *ctx)
8{
9 return (((uint64_t)ctx->count[0]) << 32) | (ctx->count[1]);
10}
11
12static void
13setCount(MD5_CTX *ctx, uint64_t count)
14{
15 ctx->count[0] = (uint32_t)(count >> 32);
16 ctx->count[1] = (uint32_t)count;
17}
18
19/* Copy a ccdigest ctx into a legacy MD5 context */
20static void
21DiToMD5(const struct ccdigest_info *di, struct ccdigest_ctx *di_ctx, MD5_CTX *md5_ctx)
22{
23 setCount(ctx: md5_ctx, ccdigest_nbits(di, di_ctx) / 8 + ccdigest_num(di, di_ctx));
24 memcpy(dst: md5_ctx->buffer, ccdigest_data(di, di_ctx), n: di->block_size);
25 memcpy(dst: md5_ctx->state, ccdigest_state_ccn(di, di_ctx), n: di->state_size);
26}
27
28/* Copy a legacy MD5 context into a ccdigest ctx */
29static void
30MD5ToDi(const struct ccdigest_info *di, MD5_CTX *md5_ctx, struct ccdigest_ctx *di_ctx)
31{
32 uint64_t count = getCount(ctx: md5_ctx);
33
34 ccdigest_num(di, di_ctx) = (unsigned)(count % di->block_size);
35 ccdigest_nbits(di, di_ctx) = (count - ccdigest_num(di, di_ctx)) * 8;
36 memcpy(ccdigest_data(di, di_ctx), src: md5_ctx->buffer, n: di->block_size);
37 memcpy(ccdigest_state_ccn(di, di_ctx), src: md5_ctx->state, n: di->state_size);
38}
39
40void
41MD5Init(MD5_CTX *ctx)
42{
43 const struct ccdigest_info *di = g_crypto_funcs->ccmd5_di;
44 ccdigest_di_decl(di, di_ctx);
45
46 g_crypto_funcs->ccdigest_init_fn(di, di_ctx);
47
48 DiToMD5(di, di_ctx, md5_ctx: ctx);
49}
50
51void
52MD5Update(MD5_CTX *ctx, const void *data, unsigned int len)
53{
54 const struct ccdigest_info *di = g_crypto_funcs->ccmd5_di;
55 ccdigest_di_decl(di, di_ctx);
56
57 MD5ToDi(di, md5_ctx: ctx, di_ctx);
58 g_crypto_funcs->ccdigest_update_fn(di, di_ctx, len, data);
59 DiToMD5(di, di_ctx, md5_ctx: ctx);
60}
61
62void
63MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx)
64{
65 const struct ccdigest_info *di = g_crypto_funcs->ccmd5_di;
66 ccdigest_di_decl(di, di_ctx);
67
68 MD5ToDi(di, md5_ctx: ctx, di_ctx);
69 ccdigest_final(di, ctx: di_ctx, digest);
70}
71