Search code examples
chashopensslpbkdf2

OpenSSL & C - Hash Passwords w/ SHA256 or SHA512


I've tried my best reading over the docs but they seem very sparing in information (maybe I'm looking in the wrong place?)

I'm trying to create a password hasher in C using OpenSSL lib in which the program can be called and passed arguments such as the ending length of the hashed password, salt length, and the HMAC used (SHA256 or 512). There just isn't a lot of info on how to utilize the API to do this.

The biggest problem I see is that there is a function called PKCS5_PBKDF2_HMAC_SHA1, but I can't find one similar for 256 or 512.. Is only SHA1 available via OpenSSL API?

Any guidance is much appreciated.


Solution

  • You can use PKCS5_PBKDF2_HMAC, which allows you to target a specific digest algorithm.

    int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, 
        const unsigned char *salt, int saltlen, 
        int iter, const EVP_MD *digest, // <<==== HERE
        int keylen, unsigned char *out);
    

    A simple example appears below, which generates a random salt, then creates a PBK from "password", the generated salt, and EVP_sha256()

    #include <openssl/evp.h>
    #include <openssl/rand.h>
    #include <openssl/bio.h>
    
    int main(int argc, char *argv[])
    {
        int iter = 1007;
    
        unsigned char salt[32] = {0};
        RAND_bytes(salt, sizeof(salt));
    
        unsigned char key[32] = {0};
        PKCS5_PBKDF2_HMAC("password", 8,
            salt, sizeof(salt),
            iter, EVP_sha256(),
            sizeof(key), key);
    
        BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE);
        BIO_dump(bio, (const char*)salt, sizeof(salt));
        BIO_dump(bio, (const char*)key, sizeof(key));
        BIO_free(bio);
    }
    

    Output (varies)

    0000 - a7 ca ac f4 43 b0 2d 48-2b f6 d5 67 7e d2 5c b4   ....C.-H+..g~.\.
    0010 - c5 82 1d 4d b1 00 cd 1e-85 91 77 4c 32 3e f3 c8   ...M......wL2>..
    0000 - 48 8f be 5a e9 1c 9e 11-d8 95 cb ed 6d 6f 36 a2   H..Z........mo6.
    0010 - 38 e6 db 95 e1 d7 a6 c0-8a 2f 3a f6 e1 74 e9 b9   8......../:..t..