Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <string.h>
#include <stdio.h>
inline char tohex(char c)
{
if ((c >= 0) && (c <= 9)) { return '0' + c; }
else { return 'a' + (c-10); }
}
// $ echo -n "data" | openssl dgst -sha1 -hmac "12345678901234567890"
// f8aa1108143b47a4ff7dc0ea02f073d877129200
int testHMAC_SHA1()
{
char* key = "12345678901234567890";
int key_len = 20;
char* data = "data";
int data_len = strlen(data);
unsigned int result_len;
unsigned char result[EVP_MAX_MD_SIZE];
int i;
HMAC(EVP_sha1(),
key, key_len,
data, data_len,
result, &result_len);
for (i=0; i<result_len; i++) {
printf("%c", tohex(result[i] >> 4));
printf("%c", tohex(result[i] & 0xF));
}
printf("\n");
}
// $ echo -n "data" | openssl dgst -sha1
// a17c9aaa61e80a1bf71d0d850af4e5baa9800bbd
int testSHA1()
{
char* data = "data";
unsigned long len = (unsigned long)strlen(data);
SHA_CTX sha_ctx;
unsigned char result[SHA_DIGEST_LENGTH];
int i;
SHA1_Init(&sha_ctx);
SHA1_Update(&sha_ctx, data, len);
SHA1_Final(result, &sha_ctx);
for (i=0; i<SHA_DIGEST_LENGTH; i++) {
printf("%c", tohex(result[i] >> 4));
printf("%c", tohex(result[i] & 0xF));
}
printf("\n");
return 0;
}
int main()
{
testSHA1();
testHMAC_SHA1();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.