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