/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>

#include <openssl/sha.h>
#include <openssl/evp.h>

/* hash: binary -> binary */
void hash(const unsigned char *content, int contentlen, unsigned char md[32])
{
    SHA256_CTX ctx;
    SHA256_Init(&ctx);
    SHA256_Update(&ctx, content, contentlen);
    SHA256_Final(md, &ctx);
}

/* Base64 encode: binary -> text */
void encode(const unsigned char *inbuf, int inbuflen, unsigned char *outbuf, int *outbuflen)
{
    EVP_ENCODE_CTX ctx;
    int len;
    EVP_EncodeInit(&ctx);
    EVP_EncodeUpdate(&ctx, outbuf, &len, inbuf, inbuflen);
    *outbuflen = len;
    EVP_EncodeFinal(&ctx, outbuf + len, &len);
    *outbuflen += len;
    if(outbuf[*outbuflen - 1] == '\n') *outbuflen -= 1;
    outbuf[*outbuflen] = '\0'; 
}

/* hash: text -> Base64 text */
void hash_encode(const char *content, char *md)
{
    unsigned char temp[32];
    int mdlen;
    hash((unsigned char *)content, strlen(content), temp);
    encode(temp, sizeof(temp), (unsigned char *)md, &mdlen);
    md[mdlen] = '\0';
}

/* test */
static const char *TEXT = "This is some random text to be used to test encryption.";
static const char *TEXT2 = "This is some random text to be used to test encryption.This is some random text to be used to test encryption.";
 
void test(char *label)
{
    char hashval[100];
    char hashval2[100];
    printf("%s:\n", label);
    hash_encode(TEXT, hashval);
    printf("  %s\n", hashval);
    hash_encode(TEXT2, hashval2);
    printf("  %s\n", hashval2);
}

void test2()
{
    char temp[100];
    hash_encode(TEXT, temp);
    if(strcmp(temp, "oJM3t4y26uLCLtiLLNP8bhZuZi24znFEdB+QnM2d0w4=") != 0)
    {
        printf("Ooops\n");
    }
}

int main()
{
    test("SHA 256 bit");
    test2();
    return 0;
}
