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