I am trying to create a self signed cert using certenroll, but I appear to be getting something wrong with the CSignerCertificate::Initialize as it throws an error 0x8009200a CRYPT_E_UNEXPECTED_MSG_TYPE.
'MyCustomRoot' is the name of my self signed root certificate that is in the Current USer->Personal->Certificates store.
public static X509Certificate2 CertOpen(string subjectName)
{
try
{
X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
try
{
var cer = store.Certificates.Find(
X509FindType.FindBySubjectName,
subjectName,
false);
if (cer.Count > 0)
{
return cer[0];
}
else
{
return null;
}
}
finally
{
store.Close();
}
}
catch
{
return null;
}
}
public static X509Certificate2 CertCreateNew(string subjectName)
{
// create DN for subject and issuer
var dn = new CX500DistinguishedName();
dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
// create a new private key for the certificate
CX509PrivateKey privateKey = new CX509PrivateKey();
privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
privateKey.MachineContext = false;
privateKey.Length = 2048;
privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
privateKey.Create();
var hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
AlgorithmFlags.AlgorithmFlagsNone, "SHA256");
// add extended key usage if you want - look at MSDN for a list of possible OIDs
var oid = new CObjectId();
oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
var oidlist = new CObjectIds();
oidlist.Add(oid);
var eku = new CX509ExtensionEnhancedKeyUsage();
eku.InitializeEncode(oidlist);
// Create the self signing request
var cert = new CX509CertificateRequestCertificate();
X509Certificate2 signer = CertOpen("MyCustomRoot");
if (signer == null)
{
throw new CryptographicException("Signer not found");
}
Console.WriteLine(signer.Subject);
String base64str = Convert.ToBase64String(signer.RawData);
ISignerCertificate signerCertificate = new CSignerCertificate();
signerCertificate.Initialize(false, X509PrivateKeyVerify.VerifySilent, EncodingType.XCN_CRYPT_STRING_BASE64, base64str);
cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, "");
cert.Subject = dn;
cert.Issuer.Encode(signer.Subject, X500NameFlags.XCN_CERT_NAME_STR_NONE);
cert.NotBefore = DateTime.Now; //start date
cert.NotAfter = DateTime.Now.AddYears(10); // expires date
cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
cert.Encode(); // encode the certificate
// this line MUST be called AFTER IX509CertificateRequestCertificate.InitializeFromPrivateKey call,
// otherwise you will get OLE_E_BLANK uninitialized object error.
cert.SignerCertificate = (CSignerCertificate)signerCertificate;
// Do the final enrollment process
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(cert); // load the certificate
enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
string csr = enroll.CreateRequest(); // Output the request in base64
// and install it back as the response
enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
PFXExportOptions.PFXExportChainWithRoot);
// instantiate the target class with the PKCS#12 data (and the empty password)
return new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), "",
// mark the private key as exportable (this is usually what you want to do)
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
);
}
Where am I going wrong?
I reproed the code and it seems that signer certificate referenced in ISignerCertificate
object returned from CertOpen
method doesn't have a private key.
To ensure this, try to add this condition in CertOpen
method:
if (cer.Count > 0 && cer[0].HasPrivateKey)
{
return cer[0];
}
User contributions licensed under CC BY-SA 3.0