Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 774
Seb Avatar asked May 10 '11 12:05

Seb


2 Answers

I've just hit this same problem. I was happening locally under the ASP.NET Development Server in VS 2010. When I executed the app under my Windows 7 / IIS 7, it worked just fine. Hope this helps!

like image 155
BNebula Avatar answered Nov 15 '22 13:11

BNebula


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.

like image 25
Russ Clarke Avatar answered Nov 15 '22 14:11

Russ Clarke