c# - 如何在 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;
}
解决方案
在更新问题中解决,只需将 SignatureAndHashAlgorithm 添加到我的签名者凭据中。
推荐阅读
- python-3.x - 如何解决使用 pip install Pillow 时出现的错误
- python - 来自 Google Composer Airflow 环境的数据存储区导出操作员权限错误
- python - Python Flask - 如何运行子进程(传递命令)?
- opencv4 - 如何为 OpenCV 4.0.1 版创建 32 位 dll 文件?
- mysql - 当我使用 POST 请求测试我的 springboot 应用程序时,电子邮件未保存在数据库中
- python - 我的代码没有运行它说有一个循环导入错误我正在尝试加载主视图以便它重定向我
- python - Python:返回下一个 30 天内相同 ID 的行
- c - 如何从文件名字符串数组中读取文件?
- c# - 如何将 TabControl 标头的文本左对齐?
- python-3.x - 计算包含列表的熊猫系列中元素的出现次数