blog.farhan.codes

Farhan's Personal and Professional Blog


SHA1 on FreeBSD Snippet

I needed some code that produces SHA1 digests for a project I am working on. I hunted through the FreeBSD’s sha1(1) code and produced this minimal snippet. Hopefully this helps someone else in the future.

// Compiled on BSD with cc shatest.c -o shatest -lmd

#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <sha.h>

#define HEX_DIGEST_LENGTH       257

int
main() {
	SHA1_CTX context;
	char buf[HEX_DIGEST_LENGTH];
	unsigned char buffer[] = "bismillah";

	SHA1_Init(&context);
	SHA1_Update(&context, buffer, strlen(buffer)); 
	printf("%s\n", SHA1_End(&context, buf));

	return 0;
}

Compile and run as follows:

$ cc shatest.c -o shatest -lmd
$ ./shatest
10d0b55e0ce96e1ad711adaac266c9200cbc27e4
$ printf "bismillah" | sha1
10d0b55e0ce96e1ad711adaac266c9200cbc27e4

Thanks to FreeBSD for maintaining such clean code!