您的位置:首页 > 运维架构

Here are the openssl HMAC sample source code.

2016-01-09 22:39 417 查看
用OpenSSL 做HMAC(C++)

#include <stdio.h>

#include <string.h>

#include <openssl/hmac.h>

int main()

{

// The key to hash

char key[] = "012345678";

// The data that we're going to hash using HMAC

char data[] = "hello world";

unsigned char* digest;

// Using sha1 hash engine here.

// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc

digest = HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);

// Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.

// Change the length accordingly with your choosen hash engine

char mdString[20];

for(int i = 0; i < 20; i++)

sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

printf("HMAC digest: %s\n", mdString);

return 0;

}

#include <stdio.h>

#include <string.h>

#include <openssl/hmac.h>

int main() {

// The secret key for hashing

const char key[] = "012345678";

// The data that we're going to hash

char data[] = "hello world";

// Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters.

// Change the length accordingly with your choosen hash engine.

unsigned char* result;

unsigned int len = 20;

result = (unsigned char*)malloc(sizeof(char) * len);

HMAC_CTX ctx;

HMAC_CTX_init(&ctx);

// Using sha1 hash engine here.

// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc

HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);

HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));

HMAC_Final(&ctx, result, &len);

HMAC_CTX_cleanup(&ctx);

printf("HMAC digest: ");

for (int i = 0; i != len; i++)

printf("%02x", (unsigned int)result[i]);

printf("\n");

free(result);

return 0;

}

Let’s try to compile both sample cpp files and you should observe the following output screenshot.

~$ gcc hmac_sample1.cpp -o sample1 -lcrypto

~$ ./sample1

HMAC digest: e19e220122b37b708bfb95aca2577905acabf0c0

~$ gcc hmac_sample2.cpp -o sample2 -lcrypto

~$ ./sample2

HMAC digest: e19e220122b37b708bfb95aca2577905acabf0c0

Note: -lcrypto will include the crypto library from openssl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: