Как создать самозаверяющий сертификат с использованием C # без закрытого ключа - PullRequest
0 голосов
/ 21 мая 2019

Я пытаюсь зашифровать текст на основе самостоятельно созданного сертификата, хотя закрытый ключ не генерируется, я обнаружил код внизу, но для меня он не генерирует закрытый ключ

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;
}

введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...