Search code examples
c#ldapmd5directoryentry

Is there a way to authenticate with DirectoryServices to LDAP using MD5?


I'm using VS 2012, C#.NET and creating a form to authenticate through LDAP.

I have this code, and it's working well:

root = new DirectoryEntry(
                "LDAP://192.168.116.20:389",
                username,
                password
            );

Both username and password are plain-text.

But I want to create a "Remember password?" checkbox where I can save the username and password md5-hashed in a file.

So, how can I authenticate using the md5-hash with DirectoryEntry and LDAP?! Is it possible?


Solution

  • If you chose to encrypt the data to a a file, you should use the System.Security.ProtectedData class.

    The data you encrypt can be bounded to the current user or the current machine that the encoding/decoding is taking place on.

    There are two simple method you should use:

    • Protect - Takes a byte array and encrypt the data.
    • Unprotect - Takes an encrypted data and returns a byte array.

    Examples:

    private static void EncryptData(string data, Stream stream)
    {
        if (stream.CanWrite == false)
                throw new IOException("Cannot write to stream.");
        var bytes = Encoding.UTF8.GetBytes(data);
        var encryptedBytes = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
        stream.Write(encryptedBytes , 0, encryptedBytes .Length);
    }
    
    private static string DecryptData(Stream stream)
    {
        if (stream.CanRead == false)
                throw new IOException("Cannot read fromstream.");
    
        using (MemoryStream memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            var encryptedBytes = memoryStream.ToArray();
            var decryptedBytes = ProtectedData.Unprotect(encryptedBytes, null, DataProtectionScope.CurrentUser)
            return Encoding.UTF8.GetString(decryptedBytes);
        }
    }
    

    Now in order to use these with a FileStream simply:

    public static void Encrypt(string password)
    {
        using (var fileStream = new FileStream(@"MyFile.dat", FileMode.Create))
        {
            EncryptData(password, fileStream);
            fileStream.Close();
        }
    }
    
    public static string Decrypt()
    {
        string password;
        using (var fileStream = new FileStream(@"MyFile.dat", FileMode.Open))
        {
            password = DecryptData(fileStream);
            fileStream.Close();
        }
        return password;
    }
    

    By the way, if you want to increase the complexity of the encryption you can pass an Entropy to the Protect and Unprotect methods. For more information see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.protect(v=vs.110).aspx