c# - 使用 X.509 证书 .pfx 文件私钥在 C# 中解密 OpenPGP
问题描述
朋友们,
我们从证书颁发机构采购了 .pfx 和 .cer 证书的 3 类证书。并将 .cer(公钥)分享给我们的合作伙伴。
加密(Java)
我们的合作伙伴使用 Java bouncy castle openpgp 标准加密消息(使用我们的公钥)并共享加密消息,如下所示,-----BEGIN PGP MESSAGE----- 版本:x v2hQEMAzFXJ94q1Nm8AQf/Tld0/3dAvgFKPQVBS8bmbXChXeApeReo1ydNS+.... .. -----结束 PGP 消息-----
解密:(C#)
我们需要使用 .pfx 文件解密消息。
我浏览了以下文章, http: //burnignorance.com/c-coding-tips/pgp-encryption-decryption-in-c/ 似乎正在生成新的 PGPKeyPair 并用于加密和解密。
但就我而言,我有 .pfx 文件我们如何从 .pfx 文件中提取 pgpprivate 密钥用于解密?您能否分享一些关于我们如何做到这一点的想法。提前感谢您为此付出的所有时间。
2020 年 13 月 12 日
我已将 X509Certificate .pfx 导入到如下所示的存储中并尝试转换 pgpprivate 密钥,
string certPath = @"C:\Users\test.pfx";
string certPass = "apples";
// Create a collection object and populate it using the PFX file
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
X509Certificate2 certificate = collection[0];
AsymmetricAlgorithm x509PrivateKey = certificate.PrivateKey;
PgpPrivateKey pK = x509PrivateKey; //Here i am gettting the invalid conversion error.
我正在尝试使用 X.509 证书私钥作为 PGPrivatekey 进行解密。但是在将私钥分配给 pgpprivatekey 时,得到了无效的强制转换异常。
有没有办法做到这一点?
问候,斯大林
解决方案
您可以尝试使用 BouncyCastle API 使用 PKCS12 类文件读取 pfx 文件,然后将密钥转换为 PgpSecretKey。
阅读有关 --> pkcs12.GetKey() 和 PgpSecretKey 类的文档。
public static void GetPriveKey(String pfxFile, String pfxPassword)
{
//Load PKCS12 file
Pkcs12Store pkcs12 = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open, FileAccess.Read), pfxPassword.ToArray());
string keyAlias = null;
foreach (string name in pkcs12.Aliases)
{
if (pkcs12.IsKeyEntry(name))
{
keyAlias = name;
break;
}
}
//
AsymmetricKeyParameter Privatekey = pkcs12.GetKey(keyAlias).Key;
X509CertificateEntry[] ce = pkcs12.GetCertificateChain(keyAlias);
AsymmetricKeyParameter PublicKey= ce[0].Certificate.GetPublicKey();
PgpSecretKey mySecretKey = new PgpSecretKey(PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
PublicKey,
Privatekey,
DateTime.UtcNow,
keyAlias,
SymmetricKeyAlgorithmTag.Cast5,
pfxPassword.ToCharArray(),
true,
null,
null,
new SecureRandom());
}
推荐阅读
- python - 按内部数组的长度降序对二维数组进行排序?
- opencv - OpenCV圆形遮罩抗锯齿
- azure - 在 Azure 门户中的 Azure Shell 文本编辑器中创建的文件在哪里?
- android - 崩溃记录的“java.lang.RuntimeException”仅在 android 8.1 (API 27) 中发生,堆栈跟踪未指向我们的代码,如何调试?
- sql-server - 获取 2 个周六前和上周五的日期
- erlang - 在 `cowboy_req` 模块中,如何在应用配置中设置 'length' 和 'period' 值?
- uwp - MS Surface LTE:如何枚举可用的 Windows.ApplicationModel.Calls.PhoneLine?
- flutter - 为什么我的底部导航栏无法正常工作?
- spring-webflux - 未找到带有 OpenApi /Swagger 规范(代码生成)文件的 Spring WebFlux
- xamarin.forms - 该应用程序已使用不包含任何设备的配置文件进行签名