views:

2895

answers:

3

how do i generate sha-1, sha-2 using openssl libarary, searched google and could not find function or any example code

+4  A: 

SHA1 is documented at http://www.openssl.org/docs/crypto/sha.html -- I'm not sure where to find docs for SHA256 &c, though.

Edit: the best "docs" I've found around are in this URL -- not much text readable to most Europeans, but click on function names &c for more detail; the logic for SHA224_*, SHA256_*, etc etc, seems to be quite similar to that documented above for SHA1.

I located an example of open source code using these functions, at this search2 .

Alex Martelli
Link dead now to non-european resource.
Amigable Clark Kant
+9  A: 

From the command line, it's simply:

echo "compute sha1" | openssl sha1


You can invoke the library like this:


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

int main()
{
    unsigned char ibuf[] = "compute sha1";
    unsigned char obuf[20];

    SHA1(ibuf, strlen(ibuf), obuf);

    int i;
    for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
    }
    printf("\n");

    return 0;
}
brianegge
+4  A: 

OpenSSL has a horrible documentation with no code examples, but here you are:

#include <openssl/sha.h>

...

SHA256_CTX context;
unsigned char md[SHA256_DIGEST_LENGTH];

SHA256_Init(&context);
SHA256_Update(&context, (unsigned char*)input, length);
SHA256_Final(md, &context);

...

Afterwards, md will contain the binary SHA-256 message digest. Similar code can be used for the other SHA family members, just replace "256" in the code.

AndiDog