Search code examples
c#asp.netwebclientnetworkcredentialscryptographicexception

NetworkCredential error in ASP.NET


I am trying to access a webpage through ASP.NET using the NetworkCredential class. However I keep getting an exception with the following message System.Security.Cryptography.CryptographicException: The handle is invalid

Below is my code on how I am trying to call the function. Any help is greatly appreciated.

C#:

System.Net.WebClient client = new System.Net.WebClient();
client.Credentials = new System.Net.NetworkCredential("Admin", "Nimda");

Stack Trace

[CryptographicException: The handle is invalid.
]

System.Security.SecureString.ProtectMemory() +154
   System.Security.SecureString.InitializeSecureString(Char* value, Int32 length) +170
   System.Security.SecureString..ctor(Char* value, Int32 length) +65
   System.Net.SecureStringHelper.CreateSecureString(String plainString) +6181188
   System.Net.NetworkCredential..ctor(String userName, String password) +64

Solution

  • Ok this is a bit awkward - I've had a look and the error is down to your windows configuration .... somewhere.

    The part of the code that's throwing an Exception is actually an interop call to a function in advapi32.dll, specifically:

    int status = Win32Native.SystemFunction040(this.m_buffer, (uint) (this.m_buffer.Length * 2), 0);
    if (status < 0)
    {
        throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
    }
    this.m_encrypted = true;
    

    Calls:

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
    internal static extern int SystemFunction040([In, Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlags);
    

    That's returning an error code, causing your exception.

    If you're in a workplace, you might want to talk with your sysadmin/network guys to see if there's anything in your local policies that might cause a failure. Otherwise, I'd see what happens if you disable your Anti-virus/disable firewall/turn of any 3rd party proxy software.

    Basically, anything that overrides default network functionality. Also, might be worth checking you have all the latest windows updates and that you dont have any virus or malware infection.

    Sorry I can't be more specific, but I don't believe this is a .Net/programming error.