Skip to content

Instantly share code, notes, and snippets.

@fador
Created August 6, 2012 10:34
Show Gist options
  • Save fador/3273298 to your computer and use it in GitHub Desktop.
Save fador/3273298 to your computer and use it in GitHub Desktop.
Java-like hex digest generation in C using openssl / libssl
/*
for mineserver ( https://github.com/fador/mineserver/ )
fador@iki.fi
*/
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
unsigned char inbuf[] = "jeb_";
SHA_CTX context;
unsigned char md[20];
char hexdigest[42];
int i;
int outpos = 0;
const char hex[] = "0123456789abcdef";
SHA1_Init(&context);
SHA1_Update(&context, (unsigned char*)inbuf, strlen(inbuf));
SHA1_Final(md, &context);
if(md[0] & 0x80)
{
unsigned char carry = 1;
hexdigest[outpos++] = '-';
for (i = 19; i >= 0; i--)
{
unsigned short twocomp = (unsigned char)~md[i];
twocomp+=carry;
if(twocomp & 0xff00)
{
twocomp = twocomp&0xff;
}
else
{
carry = 0;
}
md[i] = twocomp;
}
}
for (i = 0; i < 20; i++)
{
if(i || md[i]>>4)
{
hexdigest[outpos++] = hex[(md[i]>>4)];
}
if(i || md[i]>>4 || md[i]&0xf)
{
hexdigest[outpos++] = hex[(md[i]&0xf)];
}
}
hexdigest[outpos] = '\0';
printf("%s\n", hexdigest);
return 0;
}
// Notch -> 4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48
// jeb_ -> -7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1
// simon -> 88e16a1019277b15d58faf0541e11910eb756f6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment