DSACryptoServiceProvider constructor throws CryptographicException - c#

This code below thows the following error:
System.Security.Cryptography.CryptographicException "The handle is invalid"
CspParameters CSPParam = new System.Security.Cryptography.CspParameters(13, null, null);
CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
CSPParam.KeyContainerName = "MyKeys";
System.Security.Cryptography.DSACryptoServiceProvider r = new System.Security.Cryptography.DSACryptoServiceProvider(CSPParam); //Error occurs here
This code had been working with no issues then it started throwing this error. I can't think of anything that I have changed that relates to this. Has nayone seen this error? Any ideas of what to try?

I cannot remember everything that goes on behind the scenes in CAPI, but if I recall it can be fairly painful. By using null arguments you might get something called (I think) the default key container. I don't think you can count on the default key container not existing before you run your code, and perhaps if it exists then you get an error. You can read all about the CryptAcquireContext function and the various _KEYSET_THIS_THAT flags to learn about how to do this in unmanaged code. I have no clue if there is a .NET wrapper around that horror or not.

Make sure you have the proper permissions to do this action.
information

Related

Why different error codes for same Exception?

I am doing one synchronization example. I got two exceptions which are having same details about exception. But with the error codes.
And both exceptions have the same Inner Exceptions
What is means? What Error Codes will tell us more than exceptions?
How to get the details about my error code.
Thanks in Advance
Microsoft.Synchronization.SyncException: A storage engine operation failed with error code 25051 (HRESULT = 0x80004005, Source IID = {0FB15084-AF41-11CE-BD2B-204C4F4F5020}, Parameters=(0, 0, 0, , , , )).
Microsoft.Synchronization.SyncException: A storage engine operation failed with error code 25009 (HRESULT = 0x80004005, Source IID = {0FB15084-AF41-11CE-BD2B-204C4F4F5020}, Parameters=(0, 0, 0, , , , )).
From the wording of the message it looks like these are SQL CE errors. If so, have a look here for the meaning of the actual error codes. For .NET code that wraps native code, it is not uncommon that one managed exception, SyncException here, is used with multiple error codes in addition (most prominent example Win32Exception).
From the documentation there seems to be no apparent way to get this numeric code.
However, whether you can really react differently in your code, depending on one error code or the other, is questionable anyway. Log the error with all details
and be done with it.
Finally got cleaned after reading the documentation

C# Launching another WPF program from a byte array [duplicate]

This question already has answers here:
Load WPF application from the memory
(2 answers)
Closed 6 years ago.
First of all, let me say that I've looked through this, and i still haven't been able to find a great solution to my problem. (I will elaborate in post)
Now to the point.
I have a program which I want to secure with a login.
My setup is as follows:
Login.exe
Application.exe (Gathered from server into byte[])
The user should login, and when successfully logged in, get the server file (Application.exe) and run it, however this file must not be stored locally on the users machine. Instead, this file, which is stored as a byte array, should be launched as a program, but, if possible, not with a location on the harddrive.
Here's how the user would see it:
First they'd get the login application, login and the application
would download the file from server, and execute it.
Now the main problem i've been struggling with is, that whenever i load this byte array, i get the following Exception:
System.Reflection.TargetInvocationException: The destination of an activation triggered an exception. ---> System.InvalidOperationException: Can not create more than one instance of System.Windows.Application in the same AppDomain.
I've tried with multiple ways, but I've always ended up with the following code:
Assembly a = Assembly.Load(tmpbytearray);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o, null);
}
I've also tried with
Assembly assembly = Assembly.Load(tmpsrc);
//entrypoint: MyMainApplication.App.Main
Type type = assembly.GetType("MyMainApplication.App");
var obj = Activator.CreateInstance(type);
type.InvokeMember("Main",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
But still stuck with the same Exception.
As I've read through the reference (Section B and C) from the top I've also seen the usage of CreateInstanceFromAndUnwrap, but as I can't find a way to supply it with a byte array, instead of a file path, I've decided not to go that way.
Now I'm back to square one, and therefore asking here in my last hopes to sum up a solution to this project.
If i've made some misunderstandings throughout the post, feel free to ask, as I will do my best to be as clear and understandable as possible.
Thanks in advance!
UPDATE (Maybe another approach)
I've now thought of making a small console based application, which would act as a "launcher" for this application. However this also gives an exception:
System.Reflection.TargetInvocationException: The destination of an activation triggered an exception. ---> System.IO.IOException: The resource mainwindow.xaml was not found.
This exception is really weird, as the application itself works when ran. So the following:
Assembly a = Assembly.Load(tmpsrc);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o, null); //Exception.
}
Depending on what might be the most easy solution, what would you prefer, and how would you think of a possible solution to any of the approaches (The second, or first approach)?
(I cannot mark this as complete, but this question has now been solved)
So, some struggles later, I've finally managed to get this working.
I ended up trying many things, but the solution for me was based on this question.
I took the loader class in my Login Application and added the rest after the login has been authorized successfully:
var domain = AppDomain.CreateDomain("test");
domain.Load("Login");
var loader = (Loader)domain.CreateInstanceAndUnwrap("Login", "Login.Loader");
loader.Load(tmpsrc);
After that it somehow worked, which i'm quite surprised for. But anyways, thanks for the help and pinpoints into the proper subjects!

How do I look up a Corba service with C# and IIOP.NET?

I am writing a C# client for a Corba server and I am using IIOP.NET, going by the example on the following page: http://iiop-net.sourceforge.net/rmiAdderDNClient.html
I have gotten this far without errors:
// Register channel
IiopClientChannel channel = new IiopClientChannel();
ChannelServices.RegisterChannel(channel, false);
// Access COS naming context
CorbaInit init = CorbaInit.GetInit();
NamingContext context = init.GetNameService(host, port);
The variable "host" is a string with the computer name of the server and "port" is an int representing the port number. The values for these are currently used by other systems to connect to the server so I can confirm that they are correct.
However, trying to connect to the trader service yields an exception in runtime. Here is the code I use to do that:
// Looking up VB Trader
NameComponent[] names = new NameComponent[] { new NameComponent("TraderInterface") };
object obj = context.resolve(names);
And here is the error message I'm getting:
"CORBA system exception : omg.org.CORBA.INV_OBJREF, completed: Completed_No minor: 10102."
This seems to suggest an invalid object reference, but what does that mean? Is the string I am passing to the resolve method incorrectly formatted? I have tried many different names for this service as used in other systems, but I always get the same error, which makes me wonder whether I am even interpreting it correctly.
Incidentally, in my desperation, I have also attempted to obtain an object reference from the IOR, but this again throws a different exception (namely omg.org.CORBA.ORB_package.InvalidName).
OrbServices orb = OrbServices.GetSingleton();
object obj = orb.resolve_initial_references(traderIOR);
Any advice is welcome.
I was never able to reach my server with any of the above methods, however the following code is what finally got the communication working:
Hashtable props = new Hashtable();
props[IiopChannel.BIDIR_KEY] = true;
props[IiopServerChannel.PORT_KEY] = port;
// register corba services
IiopChannel channel = new IiopChannel(props);
ChannelServices.RegisterChannel(channel, false);
MyInterface obj = (MyInterface)RemotingServices.Connect(typeof(MyInterface), ior);
I'm not entirely sure why I had to use this (seemingly) unconventional way. Perhaps it is due to the lack of a naming service running on the server. Whatever the cause, I hope this helps somebody out there.

ActiveDirectory error 0x8000500c when traversing properties

I got the following snippet (SomeName/SomeDomain contains real values in my code)
var entry = new DirectoryEntry("LDAP://CN=SomeName,OU=All Groups,dc=SomeDomain,dc=com");
foreach (object property in entry.Properties)
{
Console.WriteLine(property);
}
It prints OK for the first 21 properties, but then fail with:
COMException {"Unknown error (0x8000500c)"}
at System.DirectoryServices.PropertyValueCollection.PopulateList()
at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
at System.DirectoryServices.PropertyCollection.PropertyEnumerator.get_Entry()
at System.DirectoryServices.PropertyCollection.PropertyEnumerator.get_Current()
at ActiveDirectory.Tests.IntegrationTests.ObjectFactoryTests.TestMethod1() in MyTests.cs:line 22
Why? How can I prevent it?
Update
It's a custom attribute that fails.
I've tried to use entry.RefreshCache() and entry.RefreshCache(new[]{"theAttributeName"}) before enumerating the properties (which didn't help).
Update2
entry.InvokeGet("theAttributeName") works (and without RefreshCache).
Can someone explain why?
Update3
It works if I supply the FQDN to the item: LDAP://srv00014.ssab.com/CN=SomeName,xxxx
Bounty
I'm looking for an answer which addresses the following:
Why entry.Properties["customAttributeName"] fails with the mentioned exception
Why entry.InvokeGet("customAttributeName") works
The cause of the exception
How to get both working
If one wants to access a custom attribute from a machine that is not
part of the domain where the custom attribute resides (the credentials
of the logged in user don't matter) one needs to pass the fully
qualified name of the object is trying to access otherwise the schema
cache on the client machine is not properly refreshed, nevermind all
the schema.refresh() calls you make
Found here. This sounds like your problem, given the updates made to the question.
Using the Err.exe tool here
http://www.microsoft.com/download/en/details.aspx?id=985
It spits out:
for hex 0x8000500c / decimal -2147463156 :
E_ADS_CANT_CONVERT_DATATYPE adserr.h
The directory datatype cannot be converted to/from a native
DS datatype
1 matches found for "0x8000500c"
Googled "The directory datatype cannot be converted to/from a native" and found this KB:
http://support.microsoft.com/kb/907462
I have the same failure. I´m read and saw a lot of questions about the error 0x8000500c by listing attribute from a DirectoryEntry.
I could see, with the Process Monitor (Sysinternals), that my process has read a schema file. This schema file is saved under
C:\Users\xxxx\AppData\Local\Microsoft\Windows\SchCache\xyz.sch.
Remove this file and the program works fine :)
I just encountered the issue and mine was with a web application.
I had this bit of code which pulls the user out of windows authentication in IIS and pulls their info from AD.
using (var context = new PrincipalContext(ContextType.Domain))
{
var name = UserPrincipal.Current.DisplayName;
var principal = UserPrincipal.FindByIdentity(context, this.user.Identity.Name);
if (principal != null)
{
this.fullName = principal.GivenName + " " + principal.Surname;
}
else
{
this.fullName = string.Empty;
}
}
This worked fine in my tests, but when I published the website it would come up with this error on FindByIdentity call.
I fixed the issue by using correct user for the app-pool of the website. As soon as I fixed that, this started working.
I had the same problem with a custom attribute of a weird data type. I had a utility program that would extract the value, but some more structured code in a service that would not.
The utility was working directly with a SearchResult object, while the service was using a DirectoryEntry.
It distilled out to this.
SearchResult result;
result.Properties[customProp]; // might work for you
result.Properties[customProp][0]; // works for me. see below
using (DirectoryEntry entry = result.GetDirectoryEntry())
{
entry.Properties[customProp]; // fails
entry.InvokeGet(customProp); // fails as well for the weird data
}
My gut feel is that the SearchResult is a little less of an enforcer and returns back whatever it has.
When this is converted to a DirectoryEntry, this code munges the weird data type so that even InvokeGet fails.
My actual extraction code with the extra [0] looks like:
byte[] bytes = (byte[])((result.Properties[customProp][0]));
String customValue = System.Text.Encoding.UTF8.GetString(bytes);
I picked up the second line from another posting on the site.

How do I update the managedBy property on a computer object in Active Directory?

In C# I write...
DirectoryEntry computer = GetComputer();
computer.Properties["managedBy"].Value = null;
computer.CommitChanges();
When I make the call to CommitChanges() it throws a COM exception
A constraint violation occurred. (Exception from HRESULT: 0x8007202F)
something is wrong with setting the "managedBy" property to null, but how else do you clear the property?
The PropertyValueCollection class also has a Clear() method which should do this for you.
You could be getting the error because the property you are setting does not presently have a value in AD yet.
I never found the answer, but I used the Linq TO AD project, and it works in this case.

Categories