有没有办法使用FtpWebRequest在C#中使用客户端证书进行FTP验证? [英] Is there a way to use FtpWebRequest to authenticate to FTP using client certificates in C#?
本文介绍了有没有办法使用FtpWebRequest在C#中使用客户端证书进行FTP验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图上传文件到FTP服务器,我需要使用客户端证书进行身份验证,而不是用户名和密码。
I am trying upload a file to a FTP server and I need to use client certificate to authenticate and not the username and password.
var fullFtpPath = String.Concat(ftpItem.FtpAddress, "/", record, ".txt");
FtpWebRequest request = (FtpWebRequest) WebRequest.Create(fullFtpPath);
request.Credentials = new NetworkCredential(ftpItem.Username, ftpItem.Password);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = ftpItem.UsePassive;
request.EnableSsl = ftpItem.UseSSL;
request.ContentLength = bytes.Length;
using(Stream s = request.GetRequestStream()) {
s.Write(bytes, 0, bytes.Length);
}
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Debug.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
db.LogExport(siteId, fullFtpPath, record, true, response.StatusDescription);
response.Close();
以上是我目前的代码,但我不确定如何实施证书认证,或者如果它是甚至可以做到这一点。我必须创建证书吗?或者服务器会为我提供一个证书,我只是将它设置在我的请求中?
Above is my current code, but I am not sure how to implement the certificate authentication or if it is even possible to do it. Do I have to create the certificate? Or the server will provide me a certificate and I will just set it in my request?
推荐答案
- 使用
FtpWebRequest.ClientCertificates
属性指定要用于身份验证的证书
- 证书的格式为 type
X509Certificate
- 您可以自行构建证书(来自字节数组或从文件导入),或者在证书存储中查看证书(
- Use
FtpWebRequest.ClientCertificates
property to specify certificate to use for authentication - The certificate is of type
X509Certificate
- You either construct the certificate on your own (from byte array or import from a file), or look it up in a certificate store (
X509Store
)
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com"); request.Credentials = new NetworkCredential("username", ""); // Query certificate from store X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); const string tp = "2b6f8ac51a85cbaf429474a55304313968667611"; X509Certificate2 cert2 = store.Certificates.Find(X509FindType.FindByThumbprint, tp, true)[0]; store.Close(); // Add certificate into request request.ClientCertificates.Add(cert2);
这篇关于有没有办法使用FtpWebRequest在C#中使用客户端证书进行FTP验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 证书的格式为 type
查看全文