无法将密钥文件添加到 X509Certificate2

MyD*_*ame 5 .net c# httpclient x509certificate2 .net-core

环境:VS 2019、Core 3.1、C# 8.0

我在尝试将 .cer 和 .key 文件添加到我的 httpClientHandler 时收到以下错误:

    {"ASN1 corrupted data."}
        Data: {System.Collections.ListDictionaryInternal}
        HResult: -2146233087
        HelpLink: null
        InnerException: null
        Message: "ASN1 corrupted data."
        Source: "System.Security.Cryptography.Algorithms"
        StackTrace: "   at System.Security.Cryptography.Asn1.AsnReader.CheckExpectedTag(Asn1Tag tag, Asn1Tag expectedTag, UniversalTagNumber tagNumber)\r\n   at System.Security.Cryptography.Asn1.AsnReader.ReadSequence(Asn1Tag expectedTag)\r\n   at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(AsnReader reader, Asn1Tag expectedTag, RSAPrivateKeyAsn& decoded)\r\n   at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(Asn1Tag expectedTag, ReadOnlyMemory`1 encoded, AsnEncodingRules ruleSet)\r\n   at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(ReadOnlyMemory`1 encoded, AsnEncodingRules ruleSet)\r\n   at System.Security.Cryptography.RSAKeyFormatHelper.FromPkcs1PrivateKey(ReadOnlyMemory`1 keyData, AlgorithmIdentifierAsn& algId, RSAParameters& ret)\r\n   at System.Security.Cryptography.RSA.ImportRSAPrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)\r\n   at BnyMellon.Program.CreateFromCertFile(String cerFile, String keyFile) in C:\\Users\\bbernzweig.AD\\source\\repos\\HttpClientExample\\
    BnyMellon\\Program.cs:line 150"
        TargetSite: {Void CheckExpectedTag(System.Security.Cryptography.Asn1.Asn1Tag, System.Security.Cryptography.Asn1.Asn1Tag, System.Security.Cryptography.Asn1.UniversalTagNumber)}
Run Code Online (Sandbox Code Playgroud)

在线此处引发错误rsa.ImportRSAPrivateKey(privateKeyBytes, out _);

private static X509Certificate2 CreateFromCertFile(string cerFile, string keyFile)
{
    try
    {
        var cert = new X509Certificate2 (cerFile);
        var privateKeyBytes = LoadPrivateKeyBytes(keyFile);

        using var rsa = RSA.Create();
        rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
        var certWithKey = cert.CopyWithPrivateKey(rsa);

        cert.Dispose();
        return certWithKey;
    }
    catch(Exception e)
    {
        Console.WriteLine(e);
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

电话来自:

var clientCertificate = new X509Certificate2();
clientCertificate = CreateFromCertFile(certificateFile, keyFile);  
httpClientHandler.ClientCertificates.Add(clientCertificate);
Run Code Online (Sandbox Code Playgroud)

注意:我可以通过curl 和Postman 使用这两个文件发出请求,没有任何问题。

我正在尝试将这两个文件附加到请求中,因此与此特定方法无关。如果有更好的方法我有兴趣听听。

090*_*9EM 6

太晚了,遇到了同样的问题ASN1 corrupted data,并设法从你的问题和@bartonjs回答的问题中解决了我的问题

关于从证书和密钥创建 X509Certificate2 而不提出 PFX 文件问题的建议是

using (RSA rsa = RSA.Create())
{
    rsa.ImportRSAPrivateKey(binaryEncoding, out _);
    // do stuff with the key now
}
Run Code Online (Sandbox Code Playgroud)

对我来说,线索是binaryEncoding,答案被评论为同一问题的一部分......

如果您有 PEM,则需要“de-PEM”它,方法是提取 BEGIN 和 END 分隔符之间的内容并运行它Convert.FromBase64String以获得binaryEncoding

因此,根据您的代码...以下导入 PEM 文件没有问题。

        private static byte[] LoadPrivateKeyBytes(string keyFile)
        {
            // remove these lines
            // -----BEGIN RSA PRIVATE KEY-----
            // -----END RSA PRIVATE KEY-----
            var pemFileData = File.ReadAllLines(keyFile).Where(x => !x.StartsWith("-"));

            // Join it all together, convert from base64
            var binaryEncoding = Convert.FromBase64String(string.Join(null, pemFileData));

            // this is the private key byte data
            return binaryEncoding;
        }

        private static X509Certificate2 CreateFromCertFile(string cerFile, string keyFile)
        {
            try
            {
                var cert = new X509Certificate2(cerFile);
                var privateKeyBytes = LoadPrivateKeyBytes(keyFile);

                using var rsa = RSA.Create();
                rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
                var certWithKey = cert.CopyWithPrivateKey(rsa);

                cert.Dispose();
                return certWithKey;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

#pragma warning disable CS8603 // Possible null reference return.
            return null;
#pragma warning restore CS8603 // Possible null reference return.
        }
Run Code Online (Sandbox Code Playgroud)

  • 我最终使用了 RestSharp 库。不敢相信找到答案有多么困难(甚至发布在 MS 的 GitHub 上)。 (2认同)