如何在C#中创建与BouncyCastle的TLS连接



我正在尝试使用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;
}

在UPDATE中解决了这个问题,只需要将SignatureAndHashAlgorithm添加到我的签名者信誉中。

最新更新