我有一个文件,该文件使用以下命令加密:
openssl smime -encrypt -aes256 -in fileToencrypt -binary -outform DEM -out encryptionFile public_key
可以使用以下命令将其解密:
openssl smime -decrypt -incryptedFile -binary -inform DEM -inkey private-key.pem -outcryptedFile
我需要在.NET Core应用程序中使用私钥(PEM格式)对其进行解密。有什么可能的解决方案?
答案 0 :(得分:0)
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace SMimeDecryptExample
{
class Program
{
static void Main (string[] args)
{
AsymmetricKeyParameter key;
using (var stream = File.OpenRead ("private-key.pem")) {
using (var reader = new StreamReader (stream)) {
var pem = new PemReader (reader);
var keyObject = pem.ReadObject ();
if (keyObject is AsymmetricCipherKeyPair pair) {
key = pair.Private;
} else if (keyObject is AsymmetricKeyParameter) {
key = (AsymmetricKeyParameter) keyObject;
}
}
}
var encryptedData = File.ReadAllBytes (args[0]);
var parser = new CmsEnvelopedDataParser (encryptedData);
var recipients = parser.GetRecipientInfos ();
byte[] decryptedData;
foreach (RecipientInformation recipient in recipients.GetRecipients ()) {
decryptedData = recipient.GetContent (key);
break;
}
// now you can do whatever you want with the decrypted data
}
}
}