zoukankan      html  css  js  c++  java
  • .net core 使用X509 私钥加密请求

    1.获取证书路径

                var basePath = _environment.ContentRootPath;
                //商户私钥证书,用于对请求报文进行签名
                var tempSignCert = new X509Certificate2(basePath + @"Cert	est.p12", "111111");

    2.数据加密

    .net core 中使用gbk encoding需要调用Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

    nuget包中使用System.Text.Encoding.CodePages

      Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
      var sha1 = SHA1.Create();
                var msg = sha1.ComputeHash(Encoding.GetEncoding("GBK").GetBytes(signeText));
                var signature = tempSignCert.GetRSAPrivateKey().SignHash(msg, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
                signeText = ToHex(signature);
                //todo 字段加密拼装
                var data= Encoding.GetEncoding("GBK").GetBytes(str);
    private static string ToHex(byte[] ba)
            {
                if (ba == null) return "";
                var buf = new char[ba.Length * 2];
    
                var p = 0;
                foreach (var b in ba)
                {
                    buf[p++] = HexChars[b >> 4];
                    buf[p++] = HexChars[b & 0x0f];
                }
                return new string(buf);
            }

    3.HttpClient请求,在handler里添加X509Certificate2 证书,数据data是byte[]类型,所以需要使用ByteArrayContent传入。

    var handler = new HttpClientHandler
    {
        ClientCertificateOptions = ClientCertificateOption.Manual,
        SslProtocols = SslProtocols.Tls12
    };
    handler.ClientCertificates.Add(tempSignCert); handler.SslProtocols
    = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
    using (var client = new HttpClient(handler))
    {
        var httpContent = new ByteArrayContent(data);               
        var response = await client.PostAsync(url, httpContent);
        var str = await response.Content.ReadAsStringAsync();
        //todo 处理数据
    }   

    以上。:)

  • 相关阅读:
    看看大对象是如何爆你的内存
    Web Api 多项目文档生成之SwaggerUI
    react-native执行 npm install cl.exe找不到 的问题
    在SourceTree中使用Git submodule
    [ElasticSearch] 如何使用中文分詞ik與繁簡轉換stconvert插件
    [Activator-HelloAkka] Create our Actors
    [Activator-HelloAkka] Define our Actors
    [Activator- HelloAkka] Define our Messages
    [Scala] Currying
    [Scala] Pattern Matching(模式匹配)
  • 原文地址:https://www.cnblogs.com/AsprosL/p/7234141.html
Copyright © 2011-2022 走看看