我正在尝试将文件上传到 FTP 服务器,我需要使用客户端证书进行身份验证,而不是用户名和密码。
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();
以上是我当前的代码,但我不确定如何实现证书身份验证,或者是否有可能实现。我必须创建证书吗?还是服务器会给我一个证书,我只需在我的请求中设置它?
最佳答案
- 使用
FtpWebRequest.ClientCertificates
property指定用于身份验证的证书 - 证书是type
X509Certificate
- 您可以自己构建证书(从字节数组或从文件导入),或者在证书存储区 (
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);
关于c# - 有没有一种方法可以使用 FtpWebRequest 在 C# 中使用客户端证书对 FTP 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109291/