disasterkid
disasterkid

Reputation: 7278

"CryptographicException: Cannot find the requested object" while the certificate file exists

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

Answers (2)

escape-llc
escape-llc

Reputation: 1331

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");
    }
    

Upvotes: 0

Willy Van den Driessche
Willy Van den Driessche

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

Related Questions