我的目标是在完全没有任何用户交互的情况下自动安装证书。
要求:
- 为当前用户安装
- 启用强大的私钥保护
- 将此 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。不知道有没有用?
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/