SHA1 example code with openssl




SHA1 :

what is SHA1:

SHA1 stands for  secure hash algorithm 1, message-digest algorithm with hash value of 20 bytes(160bit).
It  takes input message of any length  < 2^64 bits and outputs a message digest value of 160 bits.



RFC link:  http://tools.ietf.org/html/rfc3174

Designed by :  National Security Agency


Calculation SHA1 for a string.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openssl\sha.h"
#pragma comment(lib,"libeay32.lib")
#pragma comment(lib,"ssleay32.lib")
int main()
{
    printf(" first approach \n");
    unsigned char digest[SHA_DIGEST_LENGTH];   


// SHA_DIGEST_LENGTH is 20
    char demuo[]="hello";
    SHA1((unsigned char *)&demo,strlen(demo),(unsigned char *)&digest);
   
    printf(" Hash Value for SHA1 : ");
    for (int i = 0 ; i < SHA_DIGEST_LENGTH;i++)
        printf("%02x", digest[i]);

    printf("\n second approach \n");

    unsigned char digestFunction[SHA_DIGEST_LENGTH];   
    SHA_CTX cx;
    SHA1_Init(&cx);
    SHA1_Update(&cx,(unsigned char *)demo,strlen(demo));
    SHA1_Final(digestFunction,&cx);

    printf(" Hash Value for SHA1 : ");
    for (int i = 0 ; i < SHA_DIGEST_LENGTH;i++)
        printf("%02x", digestFunction[i]);


    return 0;
}



Output:

 first approach
 Hash Value for SHA1 : aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
 second approach
 Hash Value for SHA1 : aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

No comments:

Post a Comment