5

I need to understand the details of how MembershipProvider performs encryption:

  1. What algorithm does it use?
  2. Is there any base64 encoding pre-processing or post-processing?
  3. Anything extra it does in addition to the standard algorithm it uses?

Given a plain text password to encrypt, please walk me through the exact steps that produce the final encrypted password that's returned.

I think seeing the source code would go a long way in answering my questions, but I haven't been able to find it online. I have only found this documentation, which does not provide implementation details.

Thanks for any info!

10
  • I'm not sure if there are any differences in implementation between framework versions, but just so there's no confusion, to which version of .NET are you referring?
    – Cᴏʀʏ
    Sep 15, 2012 at 1:15
  • @Cory Actually let's just say the most recent version
    – Jonah
    Sep 15, 2012 at 1:16
  • 1
    I'd post the code, but it's about a hundred lines of code I don't know if I should post. I would recommend downloading a decompiler like ILSpy and then take a peek at the source code yourself. Specifically, check out System.Web.Configuration.MachineKeySection.EncryptOrDecryptData() for both .NET 2.0 and .NET 4.
    – Cᴏʀʏ
    Sep 15, 2012 at 1:23
  • 1
    It also depends on which membership provider you use. Forms provider uses a SHA1 or MD5 algorithm to Hash the password ( one way ). The SQL Membership can hash or encrypt, using either of AES, DES or TripleDES depending on configuration. You will need the machine key ( machine.config ) to replicate. The AES algorithm uses native Windows dll ( advapi32 ) to perform actual encryption, otherwise you should be able to get an open source version of the algorithms for Ruby Sep 24, 2012 at 1:12
  • 1
    For SQL provider, the default is to use AES, but you can change the algoithm by changing the system.web.machineKey config element. This is also where you find the encryption/decryption keys msdn.microsoft.com/en-us/library/w8h3skw9(v=vs.100).aspx Sep 24, 2012 at 3:25

2 Answers 2

8
+50

Below is the code that you want / need... it's a little bit of a rabbit warren getting there, so to fully understand, I would recommend doing the following:

  • Install ReSharper
    [Optional] Install dotPeek
  • Write the following code anywhere:
    var dummyMembershipProvider = new SqlMembershipProvider();
    dummyMembershipProvider.ChangePassword("userName", "oldPassword", "newPassword");
  • Ctrl + Left Click (go to definition) on ChangePassword
  • This will begin your journey down the rabbit warren... it should look something like this:
    SqlMembershipProvider.ChangePassword
    SqlMembershipProvider.EncodePassword
    MembershipProvider.EncryptPassword
    IMembershipAdapter.EncryptOrDecryptData
    MembershipAdapter.EncryptOrDecryptData
    MachineKeySection.EncryptOrDecryptData
  • Purchase ReSharper because you realise you can't live without it anymore

Anyway, here's the MachineKeySection.EncryptOrDecryptData:

public sealed class MachineKeySection : ConfigurationSection
{
    internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
                                                bool useValidationSymAlgo, bool useLegacyMode, IVType ivType)
    {
        EnsureConfig(); 

        if (useLegacyMode) 
            useLegacyMode = _UsingCustomEncryption; // only use legacy mode for custom algorithms 

        System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
        ICryptoTransform oDesEnc = GetCryptoTransform(fEncrypt, useValidationSymAlgo, useLegacyMode);
        CryptoStream cs = new CryptoStream(ms, oDesEnc, CryptoStreamMode.Write);

        // DevDiv Bugs 137864: Add Random or Hashed IV to beginning of data to be encrypted. 
        // IVType.None is used by MembershipProvider which requires compatibility even in SP2 mode.
        bool createIV = ((ivType != IVType.None) && (CompatMode > MachineKeyCompatibilityMode.Framework20SP1)); 

        if (fEncrypt && createIV)
        { 
            byte[]  iv       = null;
            int     ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
            switch (ivType)
            { 
            case IVType.Hash:
                iv = GetIVHash(buf, ivLength); 
                break; 
            case IVType.Random:
                iv = new byte[ivLength]; 
                RandomNumberGenerator.GetBytes(iv);
                break;
            }
            Debug.Assert(iv != null, "Invalid value for IVType: " + ivType.ToString("G")); 
            cs.Write(iv, 0, iv.Length);
        } 

        cs.Write(buf, start, length);
        if (fEncrypt && modifier != null) 
        {
            cs.Write(modifier, 0, modifier.Length);
        }

        cs.FlushFinalBlock();
        byte[] paddedData = ms.ToArray(); 
        byte[] bData; 
        cs.Close();
        ReturnCryptoTransform(fEncrypt, oDesEnc, useValidationSymAlgo, useLegacyMode); 

        // DevDiv Bugs 137864: Strip Random or Hashed IV from beginning of unencrypted data
        if (!fEncrypt && createIV)
        { 
            // strip off the first bytes that were either random bits or a hash of the original data
            // either way it is always equal to the key length 
            int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption); 
            int bDataLength = paddedData.Length - ivLength;

            // valid if the data is long enough to have included the padding
            if (bDataLength >= 0)
            {
                bData = new byte[bDataLength]; 
                // copy from the padded data to non-padded buffer bData.
                // dont bother with copy if the data is entirely the padding 
                if (bDataLength > 0) 
                {
                    Buffer.BlockCopy(paddedData, ivLength, bData, 0, bDataLength); 
                }
            }
            else
            { 
                // data is not padded because it is not long enough
                bData = paddedData; 
            } 
        }
        else 
        {
            bData = paddedData;
        }

        if (!fEncrypt && modifier != null && modifier.Length > 0)
        { 
            for(int iter=0; iter<modifier.Length; iter++) 
                if (bData[bData.Length - modifier.Length + iter] != modifier[iter])
                    throw new HttpException(SR.GetString(SR.Unable_to_validate_data)); 
            byte[] bData2 = new byte[bData.Length - modifier.Length];
            Buffer.BlockCopy(bData, 0, bData2, 0, bData2.Length);
            bData = bData2;
        } 
        return bData;
    } 
}
2
  • Thanks for the reply! Unfortunately I only have the VS Express, so I can't use ReSharper, so I have some followups for you: I have some test data that I want to verify against. raw password: 888888, salt: ahEvjCX3FM04S5cSi1qdHA==, encrypted pw: y3rxLUDYdj1/+IGC94/tvW6M3pQTCi/9bq1cNOUgYlM=. Given these, what inputs would go into the function you provided above? Do I also need a machine key or some other config variable? Basically, I given the raw pw and salt, I need to be able to produce the encrypted pw. Also, given the encrypted pw and salt, recover the raw. Thanks again!
    – Jonah
    Sep 18, 2012 at 0:07
  • Charlino, any chance you could answer my follow up? Would really be helpful. Thanks.
    – Jonah
    Sep 19, 2012 at 23:02
0

The source code for the membership providers is available from Microsoft. Scott Guthrie blogged about it a few years back.

http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx

8
  • 1
    Actually I downloaded ProviderToolkitSamples.msi earlier today having found that same blog post, but the source code provided is for subclasses of MembershipProvider such as SqlMembershipProvider, and those subclasses call the EncryptPassword method on the superclass. What I need is the source from the top class MembershipProvider, which is not included.
    – Jonah
    Sep 15, 2012 at 2:31
  • @Jonah - Well, your only other option is to decompile the MembershipProvider class using any of the many decompilers available. Sep 15, 2012 at 2:41
  • Can you guide a bit more, I installed .NET and VS Web Dev Express, and it appears the assemblies are in "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.ApplicationServices.dll" Do I just decompile that entire dll?
    – Jonah
    Sep 15, 2012 at 2:49
  • @Jonah - No, you decompile the class you're interested in. Download and install one of the major decompilers, like ilspy or just.decompile and it should be obvious how to use it. Sep 15, 2012 at 2:51
  • Ok I downloaded ILSpy and figured out how to use it. However, when I open up the MembershipProvider class, I see that it is abstract (i.imgur.com/RwCN1.png) and both EncryptPassword and DecryptPassword are empty virtual methods. In addition, SqlMembershipProvider, one of the files from the link in your original post, directly extends MembershipProvider, does not provide and implementation for the Encrypt/DecryptPassword methods, yet calls those methods. I thought that implied they had to be implemented by the super class, so I'm pretty confused now.
    – Jonah
    Sep 15, 2012 at 5:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.