-
Notifications
You must be signed in to change notification settings - Fork 5
/
BatchCertificateContainer.cs
87 lines (74 loc) · 2.35 KB
/
BatchCertificateContainer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
namespace X509CertificateTool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
public static class CertificateInspectorExtension
{
public static bool HasExportablePrivateKey(this X509Certificate2 certificate)
{
if (certificate == null) throw new NullReferenceException();
if (!certificate.HasPrivateKey) return false;
// TODO
return
certificate.PrivateKey is RSACryptoServiceProvider privateKey &&
privateKey.CspKeyContainerInfo != null &&
privateKey.CspKeyContainerInfo.Exportable;
}
}
internal class BatchCertificateContainer
{
internal BatchCertificateContainer() { }
internal BatchCertificateContainer(string filename, IEnumerable<CertData> certDataItems)
{
Filename = filename;
m_certs.AddRange(certDataItems);
}
internal BatchCertificateContainer(string filename)
{
Filename = filename;
Load();
}
public string Filename { get; private set;}
private readonly List<CertData> m_certs = [];
public IList<CertData> Certs
{
get { return this.m_certs; }
}
public void Store()
{
using FileStream fs = new FileStream(this.Filename, FileMode.Create, FileAccess.Write);
var xw = XmlWriter.Create(fs);
var itemsElem = new XStreamingElement("Certificates", Certs.Select(c => c.ToXElement()));
itemsElem.WriteTo(xw);
xw.Flush();
}
public void Load()
{
using FileStream fs = File.Open(this.Filename, FileMode.Open);
m_certs.Clear();
XDocument doc = XDocument.Load(XmlReader.Create(fs));
XElement root = doc.Elements().First();
var x = doc.Element("Certificates").Elements().Select(e => new CertData(e));
m_certs.AddRange(x);
}
internal void Install(Predicate<CertData> install)
{
var form = new BatchCertificateContainerImportForm(this);
if (form.ShowDialog() == DialogResult.OK)
{
foreach (CertData d in m_certs)
{
if (d.NotYetInStore && install(d))
{
d.Install();
}
}
}
}
}