Reputation: 1255
I have a large number of single certificates stored as files with .p12 extensions. I would like to combine all those certificates into one .pfx file to make less work out of importing all those certificates on client machines. Here is what I have tried. It creates the file, but the problem occurs when I import the .pfx file. The Windows Certificate Import Wizard only imports the first certificate and ignores everything after that. I assume because there is something wrong with the format of the file cause by the way I am attempting to combine them. I'm not sure of the correct way to do this. Any ideas?
private void btnCombineCerts_Click(object sender, EventArgs e)
{
String dateString = DateTime.Now.ToString("yyyyMMdd");
String timeString = DateTime.Now.ToString("hhmmssff");
String path = Directory.GetCurrentDirectory() + @"\certs\CombinedCerts\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
List<X509Certificate2> certs = new List<X509Certificate2>();
foreach(var certFile in fDialog.FileNames)
{
X509Certificate2 cert = new X509Certificate2(certFile);
certs.Add(cert);
}
foreach(X509Certificate2 cert in certs)
{
byte[] certStream = cert.Export(X509ContentType.Pfx);
using (var stream = new FileStream(path + dateString + "CombinedCerts" + timeString + ".pfx", FileMode.Append))
{
stream.Write(certStream, 0, certStream.Length);
}
}
}
Upvotes: 3
Views: 4288
Reputation: 3451
public X509Certificate2 Merge(List<X509Certificate2> certificates)
{
var certs = new X509Certificate2Collection();
foreach (var certFile in certificates)
{
certs.Add(new X509Certificate2(certFile));
}
byte[] data = certs.Export(X509ContentType.Pfx);
X509Certificate2 newFile = new X509Certificate2(data);
return newFile;
}
Upvotes: 0
Reputation: 33228
PFX inherently supports multiple certificates, but it isn't a sequential file like what you wrote. I don't know that the UI will import this properly, but it probably will if everything has a private key. The one real use of X509Certificate2Collection is that it can export or import.
var certs = new X509Certificate2Collection();
foreach (var certFile in fDialog.FileNames)
{
certs.Add(new X509Certificate2(certFile));
}
byte[] oneBigPfx = certs.Export(X509ContentType.Pfx);
File.WriteAllBytes(filename, oneBigPfx);
Upvotes: 4