views:

39

answers:

2

I have C# code as below:


        private static string password = "Password";
        private static string salt = "SALT";
        private static string hashAlgorithm = "SHA1";
        private static int iterations = 2;

        var saltValueBytes = Encoding.UTF8.GetBytes(salt);
        var passwordKey = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, iterations)
...

I need to implement the same in Mac, I came to know that Opnessl implements related methods(i.e. libcrypto).

What is the equivalent method in Opnessl to above code?

Regards
Devara Gudda

A: 

OpenSSL implements PBKDF2, which .NET exposes as Rfc2898DeriveBytes. PasswordDeriveBytes uses (according to the .NET 4 docs) "an extension of the PBKDF1 algorithm". PBKDF1 is not exposed by OpenSSL (and who knows what the 'extension' in question may be).

Using PBKDF2 (aka Rfc2898DeriveBytes) if possible will save you a lot of problems here.

Jack Lloyd
I can not change .NET code , I have to implement same encryption using OpenSSL.
Devara Gudda
+2  A: 

This shows how to implement PBKDF1 with OpenSSL, which according to the documentation is the algorithm used by PasswordDeriveBytes.

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

void pbkdf1(const char *password, const char *salt, long iter, unsigned char dk[SHA_DIGEST_LENGTH])
{
    size_t pwlen = strlen(password);
    size_t dlen = pwlen + 8;
    unsigned char *buf;

    if (dlen > SHA_DIGEST_LENGTH)
        buf = malloc(dlen);
    else
        buf = malloc(SHA_DIGEST_LENGTH);

    memcpy(buf, password, pwlen);
    strncpy((char *)buf + pwlen, salt, 8);

    while (iter-- > 0)
    {
        SHA1(buf, dlen, buf);
        dlen = SHA_DIGEST_LENGTH;
    }

    memcpy(dk, buf, SHA_DIGEST_LENGTH);
    free(buf);
}
caf
Thanks caf. But It is not matching with <code> PasswordDeriveBytes</code>. The Base64 encoding string generated by <code> PasswordDeriveBytes</code> is <code> vYJcVqBV40q+9wT/X0/MAa2nr7Epvz1u4p6LdGYNwC4= </code> . The method given by you generates string <code>809DD7DDGZ+3wzWqnqP9kAIVa5j/fwAAAAAEAAEAAAA=</code>
Devara Gudda
@Devara Gudda: PBKDF1 with SHA1 as the hash can't generate more than 20 bytes of output, but those base64 strings you've given are for 32 bytes of data, so *something* is up. You'll have to find out precisely how `PasswordDeriveBytes` differs from genuine PBKDF1.
caf