在c#中使用带有文件和密钥的X509Certificate [英] Using X509Certificate with file and key in c#
问题描述
我已将证书和密码提供给接受ssl连接的服务器。我尝试连接到这台服务器,但验证失败,主要是因为我不知道如何使用我给出的文件和密码。
I have given certificate and password to a server that accepts ssl connection. I tried to make a connection to this server but authentication fails, well mainly because I dont know how to use that file and password that I was given.
这是我的代码:
X509Certificate certificate = new X509Certificate(
@"c:\mySrvKeystore", KEY_PASSWORD);
public static bool ValidateCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", errors);
return false;
}
public void RunClient(string address, int port)
{
Console.WriteLine("Starting client...");
var client = new TcpClient(address, port);
Console.WriteLine("Client connected.");
var stream = new SslStream(client.GetStream(),false,
ValidateCertificate, null);
try
{
stream.AuthenticateAsClient(address);
Console.WriteLine(stream.IsAuthenticated ? "Client authenticated." : "Client is not authenticated.");
//TODO constantly read from server!
}
catch (AuthenticationException ae)
{
Console.WriteLine("Exception occured: {0}", ae.Message);
if (ae.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", ae.InnerException.Message);
}
Console.WriteLine("Failed to authenticate! closing the client...");
client.Close();
return;
}
catch (Exception ex)
{
Console.WriteLine("General exception occured {0}", ex.Message);
client.Close();
return;
}
}
正如您所看到的,没有代码我的代码以某种方式告诉服务器(TcpClient或SSLStream)我有这个文件和密钥!
So as you can see, there is no code in my code that somehow tells the server (either TcpClient or SSLStream) that I do have this file and key!
我有一个连接到服务器的javacode没有问题,但是我没能将它转换为c#。任何帮助都会很棒!
I have a javacode that connects to server with no problem, but I failed to convert it to c# yet. Any helps would be great!
String keyPassword = "123456";
// String keyPassword = "importkey";
try {
KeyManagerFactory keyManagerFactory;
keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyInput = new FileInputStream("c:\\mySrvKeystore");
keyStore.load(keyInput, keyPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, keyPassword.toCharArray());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory sslsocketfactory = sc.getSocketFactory();
this.sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
} catch (java.security.NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (java.security.KeyManagementException e) {
e.printStackTrace();
} catch (java.security.KeyStoreException e) {
e.printStackTrace();
} catch (java.security.cert.CertificateException e) {
e.printStackTrace();
} catch (java.security.UnrecoverableKeyException e) {
e.printStackTrace();
} finally {}
}
public void run() {
try {
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream outputstream = System.out;
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
//get text from server and stuff...no deal!
更新
根据 gtrig 将密钥转换为p12后,问题现在是 AutheneticateAsClient
方法中的IOException:
After converting the key to p12 according to gtrig the problem now is IOException in AutheneticateAsClient
method here:
try
{
var certificate = new X509Certificate2(@"d:\mySrvKeystore.p12", "123456");
X509Certificate2[] X509Certificates = {certificate};
var certsCollection = new X509CertificateCollection(X509Certificates);
//IO EXCEPTION HERE-->
stream.AuthenticateAsClient(address, certsCollection, SslProtocols.Ssl2, false);
Console.WriteLine(stream.IsAuthenticated ? "Client authenticated." : "Client is not authenticated.");
//TODO constantly read from server!
}
当我使用 SSlProtocols.Default
错误是: RemoteCertificateNameMismatch,RemoteCertificateChainErrors
推荐答案
您应该将AuthenticateAsClient与证书列表一起使用:
You should use AuthenticateAsClient with a list of certificates:
X509Certificate[] X509Certificates = { certificate };
X509CertificateCollection certsCollection = new X509CertificateCollection(X509Certificates);
sslStream.AuthenticateAsClient(address, certsCollection, SslProtocols.Default, false);
为避免证书错误:
更改
To avoid cert errors: change
public static bool ValidateCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
if (certificate != null)
{
string SendingCertificateName = "";
//List<string> Subject = CommaText(certificate.Subject); // decode commalist
// SendingCertificateName = ExtractNameValue(Subject, "CN"); // get the CN= value
report = string.Format(CultureInfo.InvariantCulture, "certificatename : {0}, SerialNumber: {1}, {2}, {3}", certificate.Subject, certificate.GetSerialNumberString(), SendingCertificateName, ServerName);
Console.WriteLine(report);
}
Console.WriteLine("Certificate error: {0}", errors);
int allow = AllowPolicyErrors << 1; // AllowPolicyErrors property allowing you to pass certain errors
return (allow & (int)sslPolicyErrors) == (int)sslPolicyErrors; // or just True if you dont't mind.
}
这篇关于在c#中使用带有文件和密钥的X509Certificate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!