c# - 自动安装p12证书文件

标签 c#

我的目标是在完全没有任何用户交互的情况下自动安装证书。

要求:

  • 为当前用户安装
  • 启用强大的私钥保护
  • 将此 key 标记为可导出
  • 将私钥安全级别设置为高 (使用此项目时需要我的许可并提供密码)

代码:

using System.Security.Cryptography.X509Certificates;
X509Certificate2 cert = new X509Certificate2(
     "file.p12", "password", 
      X509KeyStorageFlags.UserProtected
     | X509KeyStorageFlags.UserKeySet
     | X509KeyStorageFlags.Exportable);
X509Store store = new X509Store(StoreName.My);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);

以上代码在个人商店下为当前用户安装证书并能够管理第一个gui: Screenshot - Certificate Import Wizard

但它无法设置安全级别,而是打开了一个图形用户界面: Screenshot2

编辑:

there is actually a other method available via UWP called "UserCertificateEnrollmentManager.ImportPfxDataAsync Method" Link. the "KeyProtectionLevel Enum" gives you here the "ConsentWithPassword" option, but UWP is totally new for me and i would prefer to stick to the console .net

最佳答案

使用 UWP 进行测试会显示一个额外的“UWP 样式”对话框,请求同意证书操作,然后要求创建密码,因此它会跳过屏幕截图 2 中显示的 GUI。不知道有没有用?

UWP consent dialog

Windows security cert pass dialog

private async Task<string> PickPfx()
{
    var openPicker = new FileOpenPicker()
    {
        ViewMode = PickerViewMode.List,
        SuggestedStartLocation = PickerLocationId.Desktop,
    };

    openPicker.FileTypeFilter.Add(".pfx");
    openPicker.FileTypeFilter.Add(".p12");

    var file = await openPicker.PickSingleFileAsync();
    if (file == null)
        return null;

    int length = (int)(await file.GetBasicPropertiesAsync()).Size;
    byte[] bytes = new byte[length];

    using (var stream = await file.OpenStreamForReadAsync())
    {
        await stream.ReadAsync(bytes, 0, length);
    }

    return Convert.ToBase64String(bytes);
}

private async void InstallCert_Click(object sender, RoutedEventArgs e)
{
    const string CERT_PASS = "123test";

    string pfx64 = await PickPfx();
    if (pfx64 == null)
        return;

    var importParams = new PfxImportParameters()
    {
        Exportable = ExportOption.Exportable,
        FriendlyName = "My test cert",
        KeyProtectionLevel = KeyProtectionLevel.ConsentWithPassword,
    };

    var ucem = CertificateEnrollmentManager.UserCertificateEnrollmentManager;
    await ucem.ImportPfxDataAsync(pfx64, CERT_PASS, importParams);
}

关于c# - 自动安装p12证书文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58441661/

相关文章:

c# - 编译库而不检查引用

c# - .NET 2.0 : Invoking Methods Using Reflection And Generics Causes Exception

c# - 提取的文件更改修改日期

c# - Linq to XML 将元素添加到特定子树

c# - 是否有一种有效的手写文本分割算法?

c# - C#中的泛型如何提供源代码保护

c# - 将日期字符串解析为某个时区(支持夏令时)

c# - 日期时间转字符串总是默认系统时区偏移量,需要在结果中获取用户时区偏移量

c# - new UTF8Encoding(false) 仍然写 utf8 BOM

c# - 对界面对象列表进行排序