views:

448

answers:

0

I have the following code (which was borrowed from the Microsoft site) and when I run it, it shows the public and private keys being identical. This does not seem correct. In addition, when I try to USE the private key, I get the message "Object contains only the public half of a key pair. A private key must also be provided."

I am using Visual Studio 2008 on Windows XP SP3. I have no idea whether the private key is not STORED correctly or being returned correctly.

I have tried both using makecert.exe and by requesting a certificate via the certmgr management snap in, with the same results.

Any thoughts?

    private void LogCertificateLocation(StoreName storeName, StoreLocation storeLocation)
    {
        try
        {
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            log.Debug(string.Format("Number of certificates in {0}::{1}: {2}", storeName, storeLocation, fcollection.Count));
            foreach (X509Certificate2 x509 in fcollection)
            {
                if (x509.HasPrivateKey == true)
                {
                    byte[] rawdata = x509.RawData;
                    log.Debug(string.Format("         Content Type: {0}", X509Certificate2.GetCertContentType(rawdata)));
                    log.Debug(string.Format("           Thumbprint: {0}", x509.Thumbprint));
                    log.Debug(string.Format("        Friendly Name: {0}", x509.FriendlyName));
                    log.Debug(string.Format("Certificate Verified?: {0}", x509.Verify()));
                    log.Debug(string.Format("          Simple Name: {0}", x509.GetNameInfo(X509NameType.SimpleName, true)));
                    log.Debug(string.Format("  Signature Algorithm: {0}", x509.SignatureAlgorithm.FriendlyName));
                    log.Debug(string.Format("          Private Key: {0}", x509.PrivateKey.ToXmlString(false)));
                    log.Debug(string.Format("           Public Key: {0}", x509.PublicKey.Key.ToXmlString(false)));
                    log.Debug(string.Format("Certificate Archived?: {0}", x509.Archived));
                    log.Debug(string.Format("   Length of Raw Data: {0}{1}", x509.RawData.Length, Environment.NewLine));
                    x509.Reset();
                }
            }
            store.Close();
        }
        catch (CryptographicException ex)
        {
            log.Debug("Information could not be written out for this certificate.");
        }
    }