使用示例
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <hmac_sha1.h> // Generates pseudo-random data static void rand_buffer(unsigned char *buf, const long buffer_size) { long i; for (i = 0; i < buffer_size; i++) { buf[i] = rand(); } } int main(int argc, char *argv[]) { static const int MAX_KEY_SIZE = 128; uint32_t fail = 0; uint8_t key[MAX_KEY_SIZE]; uint8_t native_digest[TEST_BUFS][SHA1_DIGEST_SIZE]; uint32_t n_left = TEST_BUFS; uint32_t i = 0; uint8_t *bufs[TEST_BUFS] = { NULL }; for (i = 0; i < TEST_BUFS; i++) { bufs[i] = (uint8_t *)malloc(sizeof(uint8_t) * TEST_LEN); if (bufs[i] == NULL) { printf("malloc failed test aborted.\n"); fail = 1; goto end; } rand_buffer(bufs[i], TEST_LEN); } int keylen = rand() % MAX_KEY_SIZE + 1; rand_buffer(key, keylen); for (i = 0; i < TEST_BUFS; ) { uint32_t n_enque = 0; sha1_hmac_ctx_t hmac_ctxs[3]; sha1_hmac_ctx_t *hmac_ctx_ptrs[3] = { NULL }; sha1_hmac_key_data_t kds[3]; uint8_t *msgs[3] = { NULL }; uint64_t lens[3] = { 0 }; for (int j = 0; j < 3 && n_left > 0; j++) { hmac_sha1_key_data(key, keylen, &kds[j]); hmac_sha1_init(&hmac_ctxs[j], &kds[j]); hmac_ctx_ptrs[j] = &hmac_ctxs[j]; msgs[j] = bufs[i]; lens[j] = TEST_LEN; n_left--; n_enque++; i++; } if (n_enque == 3) { hmac_sha1_update_x3(hmac_ctx_ptrs, msgs, lens); } else if (n_enque == 2) { hmac_sha1_update_x2(hmac_ctx_ptrs, msgs, lens); } else if (n_enque == 1){ hmac_sha1_update(hmac_ctx_ptrs[0], msgs[0], lens[0]); } for (int j = 0; j < n_enque; j++) { hmac_sha1_final(hmac_ctx_ptrs[j], native_digest[i - n_enque + j]); } } if (fail == 0) { printf("PASSED\n"); } end: for (i = 0; i < TEST_BUFS; i++) { if (bufs[i] != NULL) { free(bufs[i]); bufs[i] = NULL; } } return fail; }