3 ccchmac.c -- compatibility implemenation of CCHmac functions for MD5
4 Copyright (c) 2014 Kyle J. McKay. All rights reserved.
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 #include <CommonCrypto/CommonDigest.h>
25 #define kCCHmacAlgMD5 1
29 unsigned char keydata
[CC_MD5_BLOCK_BYTES
];
33 * RFC 2104 defines the HMAC computation
34 * We only support H = MD5 (B=CC_MD5_BLOCK_BYTES)
37 extern void die(const char *err
, ...);
39 void cCCHmacInit(CCHmacContext
*ctx
, int alg
, const void *k
, size_t kl
)
43 if (alg
!= kCCHmacAlgMD5
)
44 die("cCCHmacInit requires kCCHmacAlgMD5");
46 /* 1. Get CC_MD5_BLOCK_BYTES byte key */
47 if (kl
> CC_MD5_BLOCK_BYTES
)
48 kl
= CC_MD5_BLOCK_BYTES
;
49 memcpy(ctx
->keydata
, k
, kl
);
50 if (kl
< CC_MD5_BLOCK_BYTES
)
51 memset(&ctx
->keydata
[kl
], 0, CC_MD5_BLOCK_BYTES
- kl
);
53 /* 2. XOR step 1 key with 0x36 */
54 for (i
=0; i
<CC_MD5_BLOCK_BYTES
; ++i
)
55 ctx
->keydata
[i
] ^= 0x36;
57 /* 3. Append text to the result of step 2 */
58 /* 4. Compute MD5 of result of step 3 */
59 CC_MD5_Init(&ctx
->md5ctx
);
60 CC_MD5_Update(&ctx
->md5ctx
, ctx
->keydata
, CC_MD5_BLOCK_BYTES
);
63 void cCCHmacUpdate(CCHmacContext
*ctx
, const void *d
, size_t dl
)
65 /* 3. Append text to the result of step 2 */
66 /* 4. Compute MD5 of result of step 3 */
67 CC_MD5_Update(&ctx
->md5ctx
, d
, (CC_LONG
)dl
);
70 void cCCHmacFinal(CCHmacContext
*ctx
, void *m
)
73 unsigned char md5
[CC_MD5_DIGEST_LENGTH
];
75 /* 4. Compute MD5 of result of step 3 */
76 CC_MD5_Final(md5
, &ctx
->md5ctx
);
78 /* 5. XOR step 1 key with 0x5c */
79 for (i
=0; i
<CC_MD5_BLOCK_BYTES
; ++i
)
80 ctx
->keydata
[i
] ^= (0x36 ^ 0x5c);
82 /* 6. Append MD5 result from step 4 to result of step 5 */
83 /* 7. Compute MD5 of result of step 6 and output the result */
84 CC_MD5_Init(&ctx
->md5ctx
);
85 CC_MD5_Update(&ctx
->md5ctx
, ctx
->keydata
, CC_MD5_BLOCK_BYTES
);
86 CC_MD5_Update(&ctx
->md5ctx
, md5
, CC_MD5_DIGEST_LENGTH
);
87 CC_MD5_Final(m
, &ctx
->md5ctx
);