I'm trying to write a method for creating a certificate which is not CA certificate using the RequestCertificate class and method Create. I've used this code, it created additional CA but I don't need it because I already have one:
public static void CreateCertificate4(string username, string password)
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var r = new CertificateRequest("cn=" + username, ecdsa, HashAlgorithmName.SHA256);
var cert = r.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));
string path1 = (AppDomain.CurrentDomain.BaseDirectory + @"\" + username + ".pfx");
string path2 = (AppDomain.CurrentDomain.BaseDirectory + @"\" + username + ".cer");
// Create PFX (PKCS #12) with private key
File.WriteAllBytes(path1, cert.Export(X509ContentType.Pfx, password));
// Create Base 64 encoded CER (public key only)
File.WriteAllText(path2,
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
}
I've tried to modify it and came up with this:
public static void CreateCertificate(string username, string password)
{
var certCA = GetCertificateFromStorage(StoreName.Root, StoreLocation.LocalMachine, "TestCA");
var ecdsa = ECDsa.Create();
var proba = new CertificateRequest("cn=" + username, ecdsa, HashAlgorithmName.SHA256);
var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));
string path1 = (AppDomain.CurrentDomain.BaseDirectory + @"\"+username+".pfx");
string path2 = (AppDomain.CurrentDomain.BaseDirectory + @"\"+username+".cer");
File.WriteAllBytes(path1, cert.Export(X509ContentType.Pfx, password));
// Create Base 64 encoded CER (public key only)
File.WriteAllText(path2,
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
}
There is an error in line:
var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));
as stated in the title.