Udostępnij za pośrednictwem


ASP.NET - Using the same encryption method used by ActiveDirectoryMembershipProvider to encrypt secret password answer and store it in AD

Okay, this is an interesting stuff. MembershipProvider automatically encrypts most of the sensitive information such as password, secret-question-password. What if you want to use the same encryption method yourself to encrypt data?

Before continuing reading, You need to understand and keep in mind that your <machinekey> section is the one which would be used for the encryption / decryption by the MembershipProvider. If you change it after encryption, your decryption may fail. So, please be careful while modifying anything on <machinekey> section in your web.config.

I've just created a class inheriting from MembershipProvider. I've implemented all the methods of it (just a dummy implementation - VS would be more than happy to do that for you - if you find difficulty in this, write to me; I'll help you). I've also created another new method called EncryptMe which takes a string and returns me a string which is in fact the encrypted string. This method just gets the string in bytes with RNGCryptoServiceProvider and just call the function EncryptPassword of the MembershipProvider class to do the encryption.

In fact, the EncryptPassword method is a protected method of the MembershipProvider class, and by using it, we have just achieved the same encryption which is used by the MembershipProvider class (which our ActiveDirectoryMembershipProvider also uses to encrypt your secret-password-answer). Since it is protected, you can't access it anywhere outside, but inside a derived class.

Source of my EncryptMe Function

     public string EncryptMe(string s)
    {
        byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
        byte[] data = new byte[0x10];
        new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(data);
        byte[] dst = new byte[data.Length + bytes.Length];
        Buffer.BlockCopy(data, 0, dst, 0, data.Length);
        Buffer.BlockCopy(bytes, 0, dst, data.Length, bytes.Length);
        byte[] b = EncryptPassword(dst);
        return Convert.ToBase64String(b);
    }

Now, you can just store the encrypted string to the active directory property which you've mapped to the Secret-question-password. Check this knowledge base article which explains how to modify an attribute of an user in active directory. It just talks about the properties needed by the FTP user isolation, just modify the code to use your own attribute.

Again, please make sure you do not alter your <machinekey> section which has all the information needed to encrypt and decrypt data.

Hope this helps!