2 * Copyright (C) 2012 Martin Storsjo
4 * This file is part of Libav.
6 * Libav is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libav 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 GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with Libav; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #define MAX_HASHLEN 20
29 #define MAX_BLOCKLEN 64
33 int blocklen
, hashlen
;
34 void (*final
)(void*, uint8_t*);
35 void (*update
)(void*, const uint8_t*, int len
);
37 uint8_t key
[MAX_BLOCKLEN
];
41 static void sha1_init(void *ctx
)
43 av_sha_init(ctx
, 160);
46 AVHMAC
*av_hmac_alloc(enum AVHMACType type
)
48 AVHMAC
*c
= av_mallocz(sizeof(*c
));
55 c
->init
= av_md5_init
;
56 c
->update
= av_md5_update
;
57 c
->final
= av_md5_final
;
58 c
->hash
= av_md5_alloc();
64 c
->update
= av_sha_update
;
65 c
->final
= av_sha_final
;
66 c
->hash
= av_sha_alloc();
79 void av_hmac_free(AVHMAC
*c
)
87 void av_hmac_init(AVHMAC
*c
, const uint8_t *key
, unsigned int keylen
)
90 uint8_t block
[MAX_BLOCKLEN
];
91 if (keylen
> c
->blocklen
) {
93 c
->update(c
->hash
, key
, keylen
);
94 c
->final(c
->hash
, c
->key
);
95 c
->keylen
= c
->hashlen
;
97 memcpy(c
->key
, key
, keylen
);
101 for (i
= 0; i
< c
->keylen
; i
++)
102 block
[i
] = c
->key
[i
] ^ 0x36;
103 for (i
= c
->keylen
; i
< c
->blocklen
; i
++)
105 c
->update(c
->hash
, block
, c
->blocklen
);
108 void av_hmac_update(AVHMAC
*c
, const uint8_t *data
, unsigned int len
)
110 c
->update(c
->hash
, data
, len
);
113 int av_hmac_final(AVHMAC
*c
, uint8_t *out
, unsigned int outlen
)
115 uint8_t block
[MAX_BLOCKLEN
];
117 if (outlen
< c
->hashlen
)
118 return AVERROR(EINVAL
);
119 c
->final(c
->hash
, out
);
121 for (i
= 0; i
< c
->keylen
; i
++)
122 block
[i
] = c
->key
[i
] ^ 0x5C;
123 for (i
= c
->keylen
; i
< c
->blocklen
; i
++)
125 c
->update(c
->hash
, block
, c
->blocklen
);
126 c
->update(c
->hash
, out
, c
->hashlen
);
127 c
->final(c
->hash
, out
);
131 int av_hmac_calc(AVHMAC
*c
, const uint8_t *data
, unsigned int len
,
132 const uint8_t *key
, unsigned int keylen
,
133 uint8_t *out
, unsigned int outlen
)
135 av_hmac_init(c
, key
, keylen
);
136 av_hmac_update(c
, data
, len
);
137 return av_hmac_final(c
, out
, outlen
);