在 Rust 中使用 Rustls 和 Hyper 实现 HTTPS 服务器

kan*_*udo 5 rust hyper

我正在尝试使用 Rustls 和 Hyper 来实现 HTTPS 服务器,但无法获得如何实现相同示例的正确示例。为此,我遵循并尝试了此处 hyper-rustls 存储库中给出的示例(Hyper Rustls 服务器示例)

它总是给出这个错误

FAILED: error accepting connection: TLS Error: Custom { kind: InvalidData, error: AlertReceived(CertificateUnknown) }
Run Code Online (Sandbox Code Playgroud)

我对 Rust 完全陌生,因此不知道如何通过 Hyper 正确实现 HTTPS。我也在这里经历了与此相关的问题

但还是没能找到解决办法。如果需要更多信息,请告诉我。

kre*_*reo 5

看来您的问题不在于 Hyper 或 Rust,而在于 TLS。默认情况下,当您通过 HTTPS 建立连接时,客户端会验证服务器证书的真实性。该证书需要由受信任的机构签名:有关详细信息,请参阅例如此页

要验证,请使用curl

$ curl https://localhost:1337/echo -X POST -v --insecure
...
*  SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
...
< HTTP/2 200 
< date: Sun, 12 Apr 2020 12:45:03 GMT
< 
Run Code Online (Sandbox Code Playgroud)

所以这很好用。如果删除--insecure标志,curl将拒绝建立连接:

$ curl https://localhost:1337/echo -X POST -v
...
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
Run Code Online (Sandbox Code Playgroud)

要解决此问题,您需要:

  1. 使用正确签名的证书而不是自签名的证书,或者
  2. 将您的客户端配置为不验证证书,或者
  3. 配置您的客户端以信任您的特定自签名证书。

在生产中,您唯一的选择是(1)。在开发过程中,您可以不用考虑 (2) 或 (3)。

  • 实际上,我最初使用的是来自某些 SSL 提供商的正确签名的证书,但它不适用于此代码。然后我发现问题出在“rustls”的“rsa_private_keys()”函数上,因为它只适用于 RSA 私钥。相反,我使用了`rustls`中的`pkcs8_private_keys()`,因为我的密钥以“-----BEGIN PRIVATE KEY-----”开头,而不是“-----BEGIN RSA PRIVATE KEY-----” “而且,令人惊奇的是,这就是我面临的真正问题。现在它与我真正的 SSL 证书完美配合,因此 HTTPS 完美运行。非常感谢您的帮助。 (2认同)