![](/img/trans.png)
[英]Create openssl dhparam in C# with BouncyCastle. How?
[英]How to create a TLS connection with BouncyCastle in C#?
我正在嘗試使用 C# 中的 BouncyCastle 創建具有客戶端身份驗證的 TLS 連接。 但是,我不確定如何正確設置上下文,並且我收到一個異常“TLS 1.2“signatureAndHashAlgorithm”不能為空“。 我的理解是,這來自未正確設置 TlsClient 中使用的 DefaultTlsCipherFactory。 我是否還需要像我擁有其他 Tls 類一樣擴展它,或者還有其他我遺漏的東西嗎?
var client = new TcpClient(ip.Address.ToString(), port);
var sr = new SecureRandom();
var protocol = new TlsClientProtocol(client.GetStream(), sr);
var tlsClient = new MyTlsClient(CertChainStructure, PrivateKey);
protocol.Connect(tlsClient);
下面是 MyTlsClient 和 MyTlsAuthentication 類。
class MyTlsClient : DefaultTlsClient
{
private X509CertificateStructure[] CertChain;
private AsymmetricKeyParameter PrivateKey;
public MyTlsClient(X509CertificateStructure[] certChain, AsymmetricKeyParameter privateKey)
{
CertChain = certChain;
PrivateKey = privateKey;
}
public override TlsAuthentication GetAuthentication()
{
return new MyTlsAuthentication(CertChain, PrivateKey, this.mContext);
}
}
class MyTlsAuthentication : TlsAuthentication
{
private Certificate CertChain;
private AsymmetricKeyParameter PrivateKey;
private TlsContext Context;
public MyTlsAuthentication(X509CertificateStructure[] certChain, AsymmetricKeyParameter privateKey, TlsContext context)
{
CertChain = new Certificate(certChain);
Context = context;
PrivateKey = privateKey;
}
public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
{
var creds = new DefaultTlsSignerCredentials(Context, CertChain, PrivateKey);
return creds;
}
public void NotifyServerCertificate(Certificate serverCertificate) { }
}
更新
原來問題是我沒有提供帶有憑據的簽名和哈希算法。 添加這個解決了這個問題,我能夠連接客戶端身份驗證。
public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
{
byte[] certificateTypes = certificateRequest.CertificateTypes;
if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign))
return null;
SignatureAndHashAlgorithm signatureAndHashAlgorithm = null;
if (certificateRequest.SupportedSignatureAlgorithms != null)
{
foreach (SignatureAndHashAlgorithm alg in certificateRequest.SupportedSignatureAlgorithms)
{
if (alg.Signature == SignatureAlgorithm.rsa)
{
signatureAndHashAlgorithm = alg;
break;
}
}
if (signatureAndHashAlgorithm == null)
return null;
}
var creds = new DefaultTlsSignerCredentials(mContext, CertChain, PrivateKey, signatureAndHashAlgorithm);
return creds;
}
在問題更新中解決,只需要將 SignatureAndHashAlgorithm 添加到我的簽名者信用中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.