7

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?

2
  • What is the value of certFileLocation? Also when you get the exception are you running, debugging or testing (MSTest) the code? Commented Sep 22, 2015 at 11:49
  • certFileLocation will be the location of the p12 file. This happens when I am debugging. Commented Sep 22, 2015 at 11:55

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are using MS-test, you need a couple more bits:

  1. make sure your 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!
  2. add the DeploymentItem attribute to your TestMethod. this gets it copied to your Out folder.
  3. 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"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.