Posts Tagged ‘SHA1’

Using SHA1() function

October 6, 2010 9 comments

Hi. I’ ll show you how to convert any string into a SHA1 hash using the openssl library.
To use this library you must include in your codes this:

#include <openssl/sha.h>

Moreover you have to compile the source with the “-lssl” flag.
The following code takes in input a string (argv[1]) and generates an hash string through the SHA1() function. The value of “SHA_DIGEST_LENGTH” is 20 bytes, that is the dimension of SHA1 output.
This function stores the value computed in “temp” variable.
Then in the for loop, I copy the value of “temp” into “buf”, according to the standard format of SHA1 strings.

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

int main(int argn, char *argv[]) {

	int i = 0;
	unsigned char temp[SHA_DIGEST_LENGTH];
	char buf[SHA_DIGEST_LENGTH*2];

	if ( argn != 2 ) {
		printf("Usage: %s string\n", argv[0]);
		return -1;

	memset(buf, 0x0, SHA_DIGEST_LENGTH*2);
	memset(temp, 0x0, SHA_DIGEST_LENGTH);

	SHA1((unsigned char *)argv[1], strlen(argv[1]), temp);

	for (i=0; i < SHA_DIGEST_LENGTH; i++) {
		sprintf((char*)&(buf[i*2]), "%02x", temp[i]);

	printf("SHA1 of %s is %s\n", argv[1], buf);

	return 0;


We can compile and run it as follows:

$ gcc sha.c -lssl -o sha
$ ./sha asd
SHA1 of asd is f10e2821bbbea527ea02200352313bc059445190

If you want know something else of SHA1() function you can use the manpages:

man 3 sha1

Or look up in openssl website: link


Get every new post delivered to your Inbox.