5 * Copyright (c) 2001 Marko Kreen
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * contrib/pgcrypto/px-hmac.c
36 #define HMAC_IPAD 0x36
37 #define HMAC_OPAD 0x5C
40 hmac_result_size(PX_HMAC
*h
)
42 return px_md_result_size(h
->md
);
46 hmac_block_size(PX_HMAC
*h
)
48 return px_md_block_size(h
->md
);
52 hmac_init(PX_HMAC
*h
, const uint8
*key
, unsigned klen
)
59 bs
= px_md_block_size(md
);
64 px_md_update(md
, key
, klen
);
65 px_md_finish(md
, keybuf
);
69 memcpy(keybuf
, key
, klen
);
71 for (i
= 0; i
< bs
; i
++)
73 h
->p
.ipad
[i
] = keybuf
[i
] ^ HMAC_IPAD
;
74 h
->p
.opad
[i
] = keybuf
[i
] ^ HMAC_OPAD
;
77 px_memset(keybuf
, 0, bs
);
80 px_md_update(md
, h
->p
.ipad
, bs
);
84 hmac_reset(PX_HMAC
*h
)
87 unsigned bs
= px_md_block_size(md
);
90 px_md_update(md
, h
->p
.ipad
, bs
);
94 hmac_update(PX_HMAC
*h
, const uint8
*data
, unsigned dlen
)
96 px_md_update(h
->md
, data
, dlen
);
100 hmac_finish(PX_HMAC
*h
, uint8
*dst
)
107 bs
= px_md_block_size(md
);
108 hlen
= px_md_result_size(md
);
112 px_md_finish(md
, buf
);
115 px_md_update(md
, h
->p
.opad
, bs
);
116 px_md_update(md
, buf
, hlen
);
117 px_md_finish(md
, dst
);
119 px_memset(buf
, 0, hlen
);
124 hmac_free(PX_HMAC
*h
)
128 bs
= px_md_block_size(h
->md
);
131 px_memset(h
->p
.ipad
, 0, bs
);
132 px_memset(h
->p
.opad
, 0, bs
);
139 /* PUBLIC FUNCTIONS */
142 px_find_hmac(const char *name
, PX_HMAC
**res
)
149 err
= px_find_digest(name
, &md
);
153 bs
= px_md_block_size(md
);
157 return PXE_HASH_UNUSABLE_FOR_HMAC
;
160 h
= palloc(sizeof(*h
));
161 h
->p
.ipad
= palloc(bs
);
162 h
->p
.opad
= palloc(bs
);
165 h
->result_size
= hmac_result_size
;
166 h
->block_size
= hmac_block_size
;
167 h
->reset
= hmac_reset
;
168 h
->update
= hmac_update
;
169 h
->finish
= hmac_finish
;