gpt4 book ai didi

c# - 使用 CngKey 使用 C# 在 PEM(DKIM 兼容)中生成 RSA key 对....类似于 "openssl rsa"

转载 作者:太空狗 更新时间:2023-10-29 23:52:16 25 4
gpt4 key购买 nike

是否可以生成 RSA key 对,将其导出为与 DKIM's PEM-like format 兼容的 ASN1 格式? , 仅使用 C#?

我想减少对第 3 方的依赖,但这里有一些我发现的

充气城堡

密码学应用程序 block

Win32 PFXImportCertStore

导入 PEM

Microsoft 的 CLR 安全增强

微软 CNG

这是 Microsoft CNG 提供商的代码,在 codeplex 上带有 .NET dll(上图)...但是我不知道如何在 DKIM compatible ASN1 format 中导出和导入公钥和私钥。 .

     byte[] pkcs8PrivateKey = null;
byte[] signedData = null;

CngKey key = CngKey.Create(CngAlgorithm2.Rsa);
byte[] exportedPrivateBytes = key.Export(CngKeyBlobFormat.GenericPrivateBlob);

string exportedPrivateString= Encoding.UTF8.GetString(exportedPrivateBytes);

pkcs8PrivateKey = Encoding.UTF8.GetBytes(exportedPrivateString);

using (CngKey signingKey = CngKey.Import(pkcs8PrivateKey, CngKeyBlobFormat.Pkcs8PrivateBlob))
{
using (RSACng rsa = new RSACng(signingKey))
{
rsa.SignatureHashAlgorithm = CngAlgorithm.Sha1;
signedData = rsa.SignData(dataToSign);
}
}

问题

是否有任何使用 Microsoft 库(Win32、PFX 或 Codeplex 上的 CLR)的直接示例来说明如何创建 key 对并以 PEM 格式导出/导入这些值?

最佳答案

所以您只需要一个 key 的 pkcs8。

CngKeyCreationParameters ckcParams = new CngKeyCreationParameters()
{
ExportPolicy = CngExportPolicies.AllowPlaintextExport,
KeyCreationOptions = CngKeyCreationOptions.None,
KeyUsage = CngKeyUsages.AllUsages,
};
ckcParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

myCngKey = CngKey.Create(CngAlgorithm.Rsa, null, ckcParams);

byte[] privatePlainTextBlob = myCngKey.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);
Console.WriteLine(Convert.ToBase64String(privatePlainTextBlob));
}

现在您的 key 对包含在 PKCS#8 ASN.1 编码字符串中。

关于c# - 使用 CngKey 使用 C# 在 PEM(DKIM 兼容)中生成 RSA key 对....类似于 "openssl rsa",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11266711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com