Jim*_*Jim 1 c# cryptography x509certificate2 .net-core private-key
我正在使用 GetSecretAsync() 方法从 Azure Key Vault 获取证书,然后我希望最终获得私钥和证书的 byte[]。
我的应用程序位于 .netcore3.1 这是我的代码的样子:
var certWithPrivateKey = Client.GetSecretAsync(ConfigurationSettings.AppSettings["AKVEndpoint"], ConfigurationSettings.AppSettings["CertName"]).GetAwaiter().GetResult();
var privateKeyBytes = Convert.FromBase64String(certWithPrivateKey.Value);
X509Certificate2 x509Certificate = new X509Certificate2(privateKeyBytes);
var privateKey = x509Certificate.GetRSAPrivateKey() as RSA;
Run Code Online (Sandbox Code Playgroud)
我得到了 RSACng 类型的有效私钥,但任何操作(尝试过 ExportRSAPrivateKey())都会引发“'privateKey.ExportRSAPrivateKey()' 引发类型为 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException'” 的错误和“The不支持请求的操作。”
我不知道接下来如何继续获取私钥和证书的字节[]。
因为您实际上似乎需要导出:您当前的代码不会将私钥加载为可导出,因此无法导出。解决方法是断言可导出性:
X509Certificate2 x509Certificate =
new X509Certificate2(privateKeyBytes, "", X509KeyStorageFlags.Exportable);
Run Code Online (Sandbox Code Playgroud)
如果这还不够,那么您会遇到 CAPI 可导出性和 CNG 可导出性(Windows 旧版和新版加密库)之间的差异。如果 PFX/PKCS#12 中的私钥加载到 CNG 中,则它只是“加密可导出”,但 ExportParameters 是纯文本导出。
不过,有一个解决方法......将其加密导出,然后将其导入到具有更灵活导出策略的其他位置,然后再次导出。
此代码段使用 .NET Core 3.0+ ExportPkcs8PrivateKey()方法(因为这是您希望数据采用的格式)和新的 .NET 5 PemEncoding类来简化将 DER 编码输出转换为 PEM+DER 输出的过程。如果您的导出器位于 .NET Framework 上,则这是一个更复杂的问题。对于 .NET Standard 2.0,并没有真正干净的解决方案(反映调用 .NET Core/.NET 5 的方法,否则使用 .NET Framework 的 Windows 特定版本?)。
byte[] pkcs8PrivateKey;
using (RSA privateKey = x509Certificate.GetRSAPrivateKey())
{
pkcs8PrivateKey = ExportPrivateKey(privateKey);
}
File.WriteAllText(
"tls.cer",
new string(PemEncoding.Write("CERTIFICATE", x509Certificate.RawData));
File.WriteAllText(
"tls.key",
new string(PemEncoding.Write("PRIVATE KEY", pkcs8PrivateKey));
...
private static byte[] ExportPrivateKey(RSA privateKey)
{
try
{
// If it's plaintext exportable, just do the easy thing.
return privateKey.ExportPkcs8PrivateKey();
}
catch (CryptographicException)
{
}
using (RSA exportRewriter = RSA.Create())
{
// Only one KDF iteration is being used here since it's immediately being
// imported again. Use more if you're actually exporting encrypted keys.
exportRewriter.ImportEncryptedPkcs8PrivateKey(
"password",
privateKey.ExportEncryptedPkcs8PrivateKey(
"password",
new PbeParameters(
PbeEncryptionAlgorithm.Aes128Cbc,
HashAlgorithmName.SHA256,
1)),
out _);
return exportRewriter.ExportPkcs8PrivateKey();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1852 次 |
| 最近记录: |