如何检查是否安装了ssl证书?

时间:2013-02-22 20:13:08

标签: c# windows-phone-8 ssl-certificate

我使用此代码安装自签名证书(用户必须确认安装)。

    // Constructor
    public MainPage()
    {
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);

    }
    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            StorageFolder packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder certificateFolder = await packageLocation.GetFolderAsync("Certificates");
            StorageFile certificate = await certificateFolder.GetFileAsync("myCer.cer");

            await Launcher.LaunchFileAsync(certificate);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }

是否可以检查证书是否已安装,以便每次启动应用程序时都不必安装证书?

2 个答案:

答案 0 :(得分:1)

可以通过多种方式比较证书,但最常见的两种是

  • 通过Thumbprint
  • 按序列号和发行人
    • 使用PKI时必须是唯一的
    • 比较快,因为不需要计算
    • 只有在验证链信任时才能信任。攻击者可以使用选定的序列号和颁发者名称生成自签名证书。

在代码中:

X509Certificate cert1 = /* your cert */;
X509Certificate cert2 = /* your other cert */;

// assuming you are validating pki chain
// X509Certificate compares the serial number and issuer
bool matchUsingSerialAndIssuer = cert1.Equals(cert2);

// otherwise
bool publicKeyIsIdentical = cert1.GetCertHashString() == cert2.GetCertHashString();
// or easier to read if using X509Certificate2 (Thumbprint calls GetCertHashString)
// bool publicKeyIsIdentical = cert1.Thumbprint == cert2.Thumbprint;

答案 1 :(得分:0)

为什么不尝试这样的东西来找到证书。还要将此名称空间包含在您的项目System.Security.Cryptography.X509Certificates中;如果您无法使用X509,则可以更改以下代码,以使用不同类型的证书。

 private static X509Certificate2 GetCertificateFromStore(string certSN)
        {

            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection col = store.Certificates;

                foreach (var currCert in col)
                {
                    var currSN = currCert.SerialNumber;
                    if (certSN.ToUpperInvariant() == currSN)
                    {
                        return currCert; // you found it return it
                        break;
                    }

                }

                return null; // you didnt now install it...
            }
            finally
            {
                store.Close();
            }


        }