1.获取证书路径
var basePath = _environment.ContentRootPath; //商户私钥证书,用于对请求报文进行签名 var tempSignCert = new X509Certificate2(basePath + @"\Cert\test.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 处理数据 }
以上。:)