我试图基于自行创建的证书对文本进行加密,尽管未生成私钥,但我在下面找到了代码,但对我而言它不会生成私钥
static void MakeCert()
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var req = new CertificateRequest($"cn={CNName}", ecdsa, HashAlgorithmName.SHA512);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
// Create PFX (PKCS #12) with private key
byte[] certExport = cert.Export(X509ContentType.Pkcs12,password);
File.WriteAllBytes($"{path}/{name}.pfx", certExport);
X509Certificate2 certificate = new X509Certificate2($"{path}/{name}.pfx",password);
// Create Base 64 encoded CER (public key only)
File.WriteAllText($"{path}/{name}.cer", "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
string cerFileName = $"{path}\\{name}.pfx";
}
这是我的加密方法
private static string Encrypt(X509Certificate2 certificate, string tringToEncrypt)
{
string output = string.Empty;
using (X509Store store = new X509Store(StoreLocation.CurrentUser))
{
if (!certificate.HasPrivateKey)
throw new Exception("The certificate does not have a private key");
using (RSACryptoServiceProvider cps = (RSACryptoServiceProvider)certificate.PrivateKey)
{
byte[] bytesData = Encoding.UTF8.GetBytes(stringToEncrypt);
byte[] bytesEncrypted = cps.Encrypt(bytesData, false);
output = Convert.ToBase64String(bytesEncrypted);
}
}
return output;
}