Example: hmac_sha256_base64.c
#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
/**
***********************************************************************
* @brief バッファの内容を HEX で表示
*
* @param[in] buff 表示するバッファのポインタ
* @param[in] length バッファ長
***********************************************************************
*/
static void printDump(const unsigned char *buff, int length)
{
int i;
for (i = 0; i < length; i++) {
printf("%02x", (buff[i] & 0x000000ff));
if ((i + 1) % 16 == 0) {
printf("\n");
}
else {
printf(" ");
}
}
printf("\n\n");
}
/**
***********************************************************************
* @brief バッファの内容を文字列で表示
*
* @param[in] buff 表示するバッファのポインタ
* @param[in] length バッファ長
***********************************************************************
*/
static void printChar(const unsigned char *buff, int length)
{
int i;
for (i = 0; i < length; i++) {
printf("%c", buff[i]);
}
printf("\n\n");
}
/**
***********************************************************************
* @brief BASE64 encode をする
*
* @param[in] buff Encode 対象バッファ
* @param[in] length バッファ長
***********************************************************************
*/
static void base64(const unsigned char *input, int length)
{
BIO *bmem, *b64;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
printf("Base64 output:\n");
printDump(bptr->data, bptr->length);
printf("Base64 output(char):\n");
printChar(bptr->data, bptr->length);
BIO_free_all(b64);
}
/**
***********************************************************************
* @brief hmac_sha256_base64.c のメイン関数
*
* @retval 0 正常終了
***********************************************************************
*/
int main(void)
{
const char key[] = "0123456789";
const char data[] = "abcdefghijklmnopqrstuvwxyz";
char out[EVP_MAX_MD_SIZE];
int key_len, data_len, out_len;
key_len = strlen(key);
data_len = strlen(data);
HMAC(EVP_sha256(), key, key_len, data, data_len, out, &out_len);
printf("hmac_sha256 output:\n");
printDump(out, out_len);
base64(out, out_len);
return 0;
}
crypto ライブラリをリンクするには gdi32 ライブラリが必要となる
Example: Makefile
CC = gcc
CFLAGS = -Wall
# rand_win.c で使われている CreateDCA, GetDeviceCaps などをリンクするために gdi32 ライブラリが必要
LDFLAGS = -lcrypto -lgdi32
TARGET = \
hmac_sha256_base64.exe
.SUFFIXES: .exe .c .o
.c.o:
$(CC) $(CFLAGS) -c -o $@ $<
.o.exe:
$(CC) -o $@ $< $(LDFLAGS)
default: $(TARGET)
clean:
rm -rf *.o *.exe
実行結果
> hmac_sha256_base64.exe hmac_sha256 output: c3 11 d8 1f d6 71 5e 27 b0 e3 87 7e b9 79 13 c3 1b 6a 7f 41 53 ad e5 2c 7a 42 1c d7 5e 7e 7c 65 Base64 output: 77 78 48 59 48 39 5a 78 58 69 65 77 34 34 64 2b 75 58 6b 54 77 78 74 71 66 30 46 54 72 65 55 73 65 6b 49 63 31 31 35 2b 66 47 55 3d 0a Base64 output(char): wxHYH9ZxXiew44d+uXkTwxtqf0FTreUsekIc115+fGU=
0 件のコメント:
コメントを投稿