簡體   English   中英

OpenSSL 相當於 C#,.Net Framework 4.5

[英]OpenSSL equivalent in C#, .Net Framework 4.5

使用此命令:

openssl smime -encrypt -aes-256-cbc -in input.txt -out output.txt -outform DER yourSslCertificate.pem

我可以解密(使用我的私鑰)加密文件(使用我的公鑰加密)。 是否有直接翻譯,不使用 OpenSSL,而只使用 .Net 4.5 Framework(或更低)類。 如果有幫助,我可以使用 Bouncy Castle。

私鑰是使用 openssl 創建的:

openssl req -x509 -nodes -days 100000 -newkey rsa:8912 -keyout private_key.pem -out certificate.pem

EnvelopedCms class 是內置版本,特別是如果您想要DER output。

using System.Security.Cryptography.Pkcs;

...

ContentInfo content = new ContentInfo(File.ReadAllBytes("input.txt"));
EnvelopedCms cms = new EnvelopedCms(content);
// Change the encryption algorithm to AES-256.  Not needed when decrypting.
cms.ContentEncryptionAlgorithm.Oid = new Oid("2.16.840.1.101.3.4.1.42", null);

using (X509Certificate2 cert = new X509Certificate2("yourSslCertificate.pem"))
{
    cms.Encrypt(new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, cert));
}

File.WriteAllBytes("output.txt", cms.Encode());

這種方法成功了。

openssl smime -encrypt -aes-256-cbc -in input.txt -out output.txt -outform DER yourSslCertificate.pem

public static void DecryptFileWithX509PrivateCertificate(
string inputFilePath, --path to input.txt
string outputFilePath, --path to output.txt
string privateKeyFilePath --path to yourSslCertificate.pem
)
{
    byte[] encryptedData = File.ReadAllBytes(inputFilePath);
    CmsEnvelopedDataParser parser = new CmsEnvelopedDataParser(encryptedData);
    RecipientInformationStore recipients = parser.GetRecipientInfos();
    
    PemReader pemReader = new PemReader(File.OpenText(privateKeyFilePath));
    RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)pemReader.ReadObject();
    
    foreach (RecipientInformation recipient in recipients.GetRecipients())
    {
        byte[] decryptedData = recipient.GetContent(privateKey);
        File.WriteAllBytes(outputFilePath, decryptedData);
        break;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM