Reputation: 7278
I have a .p12
certificate file and I create my certificate like this:
var certificate = new X509Certificate2(certFileLocation, "mySecret", X509KeyStorageFlags.Exportable);
When certFileLocation
is on my desktop and I give the absolute path, the code works. But when I put the entire content of the .p12 file in a new file in my solution and set the Copy to Output Directory
property of the file to "Copy if newer" I get a CryptographicException
exception that says:
Cannot find the requested object
I also check every time whether the file is in place and it is. What is the difference between these two scenarios and why can't I read the file with the latter approach?
Upvotes: 7
Views: 9327
Reputation: 1331
If you are using MS-test, you need a couple more bits:
runsettings
are configured to NOT Delete Folders after tests are complete if you want to see any output after-the-fact; this caused me 30 minutes of lost time!DeploymentItem
attribute to your TestMethod
. this gets it copied to your Out
folder.use the TestContext.DeploymentDirectory
as your "root" folder:
X509Certificate2 GetCert()
{
var stx = File.Open(Path.Combine(TestContext.DeploymentDirectory, "thecertfile.pfx"), FileMode.Open);
using (BinaryReader br = new BinaryReader(stx))
{
return new X509Certificate2(br.ReadBytes((int)br.BaseStream.Length), "password");
}
}
[TestMethod, DeploymentItem("thecertfile.pfx")]
public void Signing_FlameTest()
{
var cert = GetCert();
Assert.IsNotNull(cert, "GetCert failed");
}
Upvotes: 0
Reputation: 1759
I had a similar problem. It worked with a fixed file but did not work with the file relative to my unit tests. This was so mindnumbling that I finally had a look at the files and compared them binary. They where not the same. They were read and written as strings, which caused them to be slightly different due to unicode interpretations. When I copied them myself (from a resourcestream) as binary (byte[]), everything worked again. I hope this solves your problem too.
Upvotes: 4