Node.js v20.18.0 文档


TLS (SSL)#

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: lib/tls.js

node:tls 模块提供了构建在 OpenSSL 之上的传输层安全 (TLS) 和安全套接字层 (SSL) 协议的实现。该模块可以使用以下方式访问:

¥The node:tls module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using:

const tls = require('node:tls'); 

确定加密支持是否不可用#

¥Determining if crypto support is unavailable

可以在不支持 node:crypto 模块的情况下构建 Node.js。在这种情况下,尝试 import tls 或调用 require('node:tls') 将导致抛出错误。

¥It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from tls or calling require('node:tls') will result in an error being thrown.

使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:

¥When using CommonJS, the error thrown can be caught using try/catch:

let tls;
try {
  tls = require('node:tls');
} catch (err) {
  console.error('tls support is disabled!');
} 

当使用词法 ESM import 关键字时,只有在尝试加载模块(例如,使用预加载模块)之前注册了 process.on('uncaughtException') 的处理程序时,才能捕获错误。

¥When using the lexical ESM import keyword, the error can only be caught if a handler for process.on('uncaughtException') is registered before any attempt to load the module is made (using, for instance, a preload module).

使用 ESM 时,如果有可能在未启用加密支持的 Node.js 版本上运行代码,则考虑使用 import() 函数而不是 import 关键字:

¥When using ESM, if there is a chance that the code may be run on a build of Node.js where crypto support is not enabled, consider using the import() function instead of the lexical import keyword:

let tls;
try {
  tls = await import('node:tls');
} catch (err) {
  console.error('tls support is disabled!');
} 

TLS/SSL 概念#

¥TLS/SSL concepts

TLS/SSL 是一组协议,它依赖于公钥基础设施 (PKI) 来实现客户端和服务器之间的安全通信。对于最常见的情况,每个服务器都必须有私钥。

¥TLS/SSL is a set of protocols that rely on a public key infrastructure (PKI) to enable secure communication between a client and a server. For most common cases, each server must have a private key.

可以通过多种方式生成私钥。以下示例说明了使用 OpenSSL 命令行接口生成 2048 位 RSA 私钥:

¥Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private key:

openssl genrsa -out ryans-key.pem 2048 

使用 TLS/SSL,所有服务器(和一些客户端)都必须有一个证书。证书是与私钥相对应的公钥,由证书颁发机构或私钥所有者进行数字签名(此类证书称为 "self-signed")。获取证书的第一步是创建证书签名请求 (CSR) 文件。

¥With TLS/SSL, all servers (and some clients) must have a certificate. Certificates are public keys that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first step to obtaining a certificate is to create a Certificate Signing Request (CSR) file.

OpenSSL 命令行接口可用于为私钥生成 CSR:

¥The OpenSSL command-line interface can be used to generate a CSR for a private key:

openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem 

一旦生成 CSR 文件,则它可以发送到证书颁发机构进行签名或用于生成自签名证书。

¥Once the CSR file is generated, it can either be sent to a Certificate Authority for signing or used to generate a self-signed certificate.

使用 OpenSSL 命令行接口创建自签名证书如以下示例所示:

¥Creating a self-signed certificate using the OpenSSL command-line interface is illustrated in the example below:

openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem 

生成证书后,可用于生成 .pfx.p12 文件:

¥Once the certificate is generated, it can be used to generate a .pfx or .p12 file:

openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
      -certfile ca-cert.pem -out ryans.pfx 

在哪里:

¥Where:

  • in:是签名的证书

    ¥in: is the signed certificate

  • inkey:是关联的私钥

    ¥inkey: is the associated private key

  • certfile:是将所有证书颁发机构 (CA) 证书串联到一个文件中,例如 cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

    ¥certfile: is a concatenation of all Certificate Authority (CA) certs into a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

完美前向保密#

¥Perfect forward secrecy

术语 前向保密 或完全前向保密描述了密钥协商(即密钥交换)方法的一个特性。也就是说,服务器和客户端密钥用于协商新的临时密钥,这些密钥专门用于且仅用于当前通信会话。实际上,这意味着即使服务器的私钥被泄露,如果攻击者设法获得专门为会话生成的密钥对,通信也只能被窃听者解密。

¥The term forward secrecy or perfect forward secrecy describes a feature of key-agreement (i.e., key-exchange) methods. That is, the server and client keys are used to negotiate new temporary keys that are used specifically and only for the current communication session. Practically, this means that even if the server's private key is compromised, communication can only be decrypted by eavesdroppers if the attacker manages to obtain the key-pair specifically generated for the session.

完美前向保密是通过在每次 TLS/SSL 握手时随机生成密钥对的密钥对来实现的(与对所有会话使用相同的密钥相反)。实现此技术的方法称为 "ephemeral"。

¥Perfect forward secrecy is achieved by randomly generating a key pair for key-agreement on every TLS/SSL handshake (in contrast to using the same key for all sessions). Methods implementing this technique are called "ephemeral".

目前通常使用两种方法来实现完全前向保密(注意传统缩写后面附加的字符 "E"):

¥Currently two methods are commonly used to achieve perfect forward secrecy (note the character "E" appended to the traditional abbreviations):

  • ECDHE:椭圆曲线 Diffie-Hellman 密钥协议的临时版本。

    ¥ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman key-agreement protocol.

  • DHE:Diffie-Hellman 密钥协议的临时版本。

    ¥DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.

默认情况下启用使用 ECDHE 的完美前向保密。在创建 TLS 服务器时可以使用 ecdhCurve 选项来自定义要使用的支持的 ECDH 曲线列表。有关详细信息,请参阅 tls.createServer()

¥Perfect forward secrecy using ECDHE is enabled by default. The ecdhCurve option can be used when creating a TLS server to customize the list of supported ECDH curves to use. See tls.createServer() for more info.

DHE 默认禁用,但可以通过将 dhparam 选项设置为 'auto' 与 ECDHE 一起启用。还支持自定义 DHE 参数,但不鼓励使用自动选择的众所周知的参数。

¥DHE is disabled by default but can be enabled alongside ECDHE by setting the dhparam option to 'auto'. Custom DHE parameters are also supported but discouraged in favor of automatically selected, well-known parameters.

完美前向保密在 TLSv1.2 之前是可选的。从 TLSv1.3 开始,始终使用 (EC)DHE(仅 PSK 连接除外)。

¥Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is always used (with the exception of PSK-only connections).

ALPN 和 SNI#

¥ALPN and SNI

ALPN(应用层协议协商扩展)和 SNI(服务器名称指示)是 TLS 握手扩展:

¥ALPN (Application-Layer Protocol Negotiation Extension) and SNI (Server Name Indication) are TLS handshake extensions:

  • ALPN:允许将一个 TLS 服务器用于多个协议(HTTP、HTTP/2)

    ¥ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)

  • SNI:允许对具有不同证书的多个主机名使用一个 TLS 服务器。

    ¥SNI: Allows the use of one TLS server for multiple hostnames with different certificates.

预共享密钥#

¥Pre-shared keys

TLS-PSK 支持可作为普通基于证书的身份验证的替代方法。它使用预共享密钥而不是证书来验证 TLS 连接,提供相互验证。TLS-PSK 和公钥基础设施并不相互排斥。客户端和服务器可以同时容纳两者,在正常的密码协商步骤中选择它们中的任何一个。

¥TLS-PSK support is available as an alternative to normal certificate-based authentication. It uses a pre-shared key instead of certificates to authenticate a TLS connection, providing mutual authentication. TLS-PSK and public key infrastructure are not mutually exclusive. Clients and servers can accommodate both, choosing either of them during the normal cipher negotiation step.

TLS-PSK 只是一个不错的选择,因为存在与每台连接机器安全共享密钥的方法,因此它不会取代大多数 TLS 使用的公钥基础设施(PKI)。OpenSSL 中的 TLS-PSK 实现近年来出现了许多安全漏洞,主要是因为它仅被少数应用使用。在切换到 PSK 密码之前,请考虑所有替代解决方案。在生成 PSK 时,使用 RFC 4086 中讨论的足够的熵至关重要。从密码或其他低熵来源导出共享秘密是不安全的。

¥TLS-PSK is only a good choice where means exist to securely share a key with every connecting machine, so it does not replace the public key infrastructure (PKI) for the majority of TLS uses. The TLS-PSK implementation in OpenSSL has seen many security flaws in recent years, mostly because it is used only by a minority of applications. Please consider all alternative solutions before switching to PSK ciphers. Upon generating PSK it is of critical importance to use sufficient entropy as discussed in RFC 4086. Deriving a shared secret from a password or other low-entropy sources is not secure.

默认情况下禁用 PSK 密码,因此使用 TLS-PSK 需要使用 ciphers 选项明确指定密码套件。可用密码列表可以通过 openssl ciphers -v 'PSK' 检索。所有 TLS 1.3 密码都符合 PSK 的条件,并且可以通过 openssl ciphers -v -s -tls1_3 -psk 检索。在客户端连接上,应该传递自定义 checkServerIdentity,因为如果没有证书,默认 checkServerIdentity 将失败。

¥PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the ciphers option. The list of available ciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3 ciphers are eligible for PSK and can be retrieved via openssl ciphers -v -s -tls1_3 -psk. On the client connection, a custom checkServerIdentity should be passed because the default one will fail in the absence of a certificate.

根据 RFC 4279,必须支持长度最大为 128 字节的 PSK 标识和长度最大为 64 字节的 PSK。从 OpenSSL 1.1.0 开始,最大身份大小为 128 字节,最大 PSK 长度为 256 字节。

¥According to the RFC 4279, PSK identities up to 128 bytes in length and PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0 maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

由于底层 OpenSSL API 的限制,当前的实现不支持异步 PSK 回调。

¥The current implementation doesn't support asynchronous PSK callbacks due to the limitations of the underlying OpenSSL API.

要使用 TLS-PSK,客户端和服务器必须指定 pskCallback 选项,该函数返回要使用的 PSK(必须与所选密码的摘要兼容)。

¥To use TLS-PSK, client and server must specify the pskCallback option, a function that returns the PSK to use (which must be compatible with the selected cipher's digest).

它将首先在客户端上调用:

¥It will be called first on the client:

  • 暗示:<string> 可选消息从服务器发送,以帮助客户端决定在协商期间使用哪个身份。如果使用 TLS 1.3,则始终为 null

    ¥hint: <string> optional message sent from the server to help the client decide which identity to use during negotiation. Always null if TLS 1.3 is used.

  • 返回:<Object> 的形式为 { psk: <Buffer|TypedArray|DataView>, identity: <string> }null

    ¥Returns: <Object> in the form { psk: <Buffer|TypedArray|DataView>, identity: <string> } or null.

然后在服务器上:

¥Then on the server:

null 的返回值会停止协商过程并向另一方发送 unknown_psk_identity 警报消息。如果服务器希望隐藏 PSK 身份未知的事实,回调必须提供一些随机数据作为 psk,以使与 decrypt_error 的连接在协商完成之前失败。

¥A return value of null stops the negotiation process and sends an unknown_psk_identity alert message to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as psk to make the connection fail with decrypt_error before negotiation is finished.

客户端发起的重新协商攻击缓解#

¥Client-initiated renegotiation attack mitigation

TLS 协议允许客户端重新协商 TLS 会话的某些方面。不幸的是,会话重新协商需要不成比例的服务器端资源,使其成为拒绝服务攻击的潜在载体。

¥The TLS protocol allows clients to renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount of server-side resources, making it a potential vector for denial-of-service attacks.

为了降低风险,每十分钟重新协商的次数限制为 3 次。当超过此阈值时,tls.TLSSocket 实例上会触发 'error' 事件。限制是可配置的:

¥To mitigate the risk, renegotiation is limited to three times every ten minutes. An 'error' event is emitted on the tls.TLSSocket instance when this threshold is exceeded. The limits are configurable:

  • tls.CLIENT_RENEG_LIMIT <number> 指定重新协商请求的数量。默认值:3

    ¥tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation requests. Default: 3.

  • tls.CLIENT_RENEG_WINDOW <number> 指定时间重新协商窗口(以秒为单位)。默认值:600(10 分钟)。

    ¥tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window in seconds. Default: 600 (10 minutes).

在没有充分了解影响和风险的情况下,不应修改默认的重新协商限制。

¥The default renegotiation limits should not be modified without a full understanding of the implications and risks.

TLSv1.3 不支持重新协商。

¥TLSv1.3 does not support renegotiation.

会话恢复#

¥Session resumption

建立 TLS 会话可能相对较慢。可以通过保存并稍后重用会话状态来加快进程。有几种机制可以做到这一点,这里从最旧到最新(和首选)进行了讨论。

¥Establishing a TLS session can be relatively slow. The process can be sped up by saving and later reusing the session state. There are several mechanisms to do so, discussed here from oldest to newest (and preferred).

会话标识符#

¥Session identifiers

服务器为新连接生成唯一的 ID 并将其发送给客户端。客户端和服务器保存会话状态。当重新连接时,客户端发送其保存的会话状态的 ID,如果服务器也有该 ID 的状态,它可以同意使用它。否则,服务器将创建新的会话。有关详细信息,请参阅第 23 和 30 页的 RFC 2246

¥Servers generate a unique ID for new connections and send it to the client. Clients and servers save the session state. When reconnecting, clients send the ID of their saved session state and if the server also has the state for that ID, it can agree to use it. Otherwise, the server will create a new session. See RFC 2246 for more information, page 23 and

当触发 HTTPS 请求时,大多数网络浏览器都支持使用会话标识符恢复。

¥Resumption using session identifiers is supported by most web browsers when making HTTPS requests.

对于 Node.js,客户端等待 'session' 事件获取会话数据,并将数据提供给后续 tls.connect()session 选项以重用会话。服务器必须为 'newSession''resumeSession' 事件实现句柄,以使用会话 ID 作为查找键来保存和恢复会话数据以重用会话。要在负载均衡器或集群工作器之间重用会话,服务器必须在其会话处理程序中使用共享会话缓存(例如 Redis)。

¥For Node.js, clients wait for the 'session' event to get the session data, and provide the data to the session option of a subsequent tls.connect() to reuse the session. Servers must implement handlers for the 'newSession' and 'resumeSession' events to save and restore the session data using the session ID as the lookup key to reuse sessions. To reuse sessions across load balancers or cluster workers, servers must use a shared session cache (such as Redis) in their session handlers.

会话门票#

¥Session tickets

服务器加密整个会话状态并将其作为 "ticket" 发送给客户端。当重新连接时,在初始连接时将状态发送到服务器。此机制避免了对服务器端会话缓存的需要。如果服务器不使用票证,出于任何原因(无法解密、太旧等),则它将创建新的会话并发送新的票证。有关详细信息,请参阅 RFC 5077

¥The servers encrypt the entire session state and send it to the client as a "ticket". When reconnecting, the state is sent to the server in the initial connection. This mechanism avoids the need for a server-side session cache. If the server doesn't use the ticket, for any reason (failure to decrypt it, it's too old, etc.), it will create a new session and send a new ticket. See RFC 5077 for more information.

当触发 HTTPS 请求时,许多网络浏览器普遍支持使用会话票证恢复。

¥Resumption using session tickets is becoming commonly supported by many web browsers when making HTTPS requests.

对于 Node.js,客户端使用相同的 API 来恢复会话标识符和恢复会话票证。用于调试,如果 tls.TLSSocket.getTLSTicket() 返回值,则会话数据包含票证,否则包含客户端会话状态。

¥For Node.js, clients use the same APIs for resumption with session identifiers as for resumption with session tickets. For debugging, if tls.TLSSocket.getTLSTicket() returns a value, the session data contains a ticket, otherwise it contains client-side session state.

使用 TLSv1.3,请注意服务器可能会发送多个票证,从而导致多个 'session' 事件,请参阅 'session' 了解更多信息。

¥With TLSv1.3, be aware that multiple tickets may be sent by the server, resulting in multiple 'session' events, see 'session' for more information.

单进程服务器不需要特定的实现来使用会话票证。要在服务器重新启动或负载平衡器之间使用会话票证,服务器必须都具有相同的票证密钥。内部有三个 16 字节的密钥,但 tls API 为方便起见将它们公开为单个 48 字节的缓冲区。

¥Single process servers need no specific implementation to use session tickets. To use session tickets across server restarts or load balancers, servers must all have the same ticket keys. There are three 16-byte keys internally, but the tls API exposes them as a single 48-byte buffer for convenience.

可以通过在一个服务器实例上调用 server.getTicketKeys() 来获取票证密钥然后分发它们,但是更合理的是安全地生成 48 字节的安全随机数据并使用 tls.createServer()ticketKeys 选项设置它们。应该定期重新生成密钥,并且可以使用 server.setTicketKeys() 重置服务器的密钥。

¥It's possible to get the ticket keys by calling server.getTicketKeys() on one server instance and then distribute them, but it is more reasonable to securely generate 48 bytes of secure random data and set them with the ticketKeys option of tls.createServer(). The keys should be regularly regenerated and server's keys can be reset with server.setTicketKeys().

会话票证密钥是加密密钥,必须安全存储。使用 TLS 1.2 及更低版本,如果它们被泄露,所有使用用它们加密的票证的会话都可以解密。它们不应该存储在磁盘上,应该定期重新生成。

¥Session ticket keys are cryptographic keys, and they must be stored securely. With TLS 1.2 and below, if they are compromised all sessions that used tickets encrypted with them can be decrypted. They should not be stored on disk, and they should be regenerated regularly.

如果客户端宣传支持票证,则服务器将发送它们。服务器可以通过在 secureOptions 中提供 require('node:constants').SSL_OP_NO_TICKET 来禁用票证。

¥If clients advertise support for tickets, the server will send them. The server can disable tickets by supplying require('node:constants').SSL_OP_NO_TICKET in secureOptions.

会话标识符和会话票证都超时,导致服务器创建新会话。超时时间可以用 tls.createServer()sessionTimeout 选项配置。

¥Both session identifiers and session tickets timeout, causing the server to create new sessions. The timeout can be configured with the sessionTimeout option of tls.createServer().

对于所有机制,当恢复失败时,服务器将创建新会话。由于无法恢复会话不会导致 TLS/HTTPS 连接失败,所以很容易不会注意到 TLS 性能不必要的糟糕。OpenSSL CLI 可用于验证服务器是否正在恢复会话。使用 -reconnect 选项到 openssl s_client,例如:

¥For all the mechanisms, when resumption fails, servers will create new sessions. Since failing to resume the session does not cause TLS/HTTPS connection failures, it is easy to not notice unnecessarily poor TLS performance. The OpenSSL CLI can be used to verify that servers are resuming sessions. Use the -reconnect option to openssl s_client, for example:

openssl s_client -connect localhost:443 -reconnect 

通过调试输出读取。第一个连接应该是 "新的",例如:

¥Read through the debug output. The first connection should say "New", for example:

New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 

后续连接应为 "重复使用",例如:

¥Subsequent connections should say "Reused", for example:

Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 

修改默认的 TLS 密码套件#

¥Modifying the default TLS cipher suite

Node.js 是使用默认的启用和禁用 TLS 密码套件构建的。这个默认密码列表可以在构建 Node.js 时配置,以允许发行版提供自己的默认列表。

¥Node.js is built with a default suite of enabled and disabled TLS ciphers. This default cipher list can be configured when building Node.js to allow distributions to provide their own default list.

以下命令可用于显示默认密码套件:

¥The following command can be used to show the default cipher suite:

node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA256
ECDHE-RSA-AES256-SHA384
DHE-RSA-AES256-SHA384
ECDHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA256
HIGH
!aNULL
!eNULL
!EXPORT
!DES
!RC4
!MD5
!PSK
!SRP
!CAMELLIA 

可以使用 --tls-cipher-list 命令行开关(直接或通过 NODE_OPTIONS 环境变量)完全替换此默认值。例如,以下使 ECDHE-RSA-AES128-GCM-SHA256:!RC4 成为默认的 TLS 密码套件:

¥This default can be replaced entirely using the --tls-cipher-list command-line switch (directly, or via the NODE_OPTIONS environment variable). For instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS cipher suite:

node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js

export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js 

为了验证,使用以下命令显示设置的密码列表,注意 defaultCoreCipherListdefaultCipherList 之间的区别:

¥To verify, use the following command to show the set cipher list, note the difference between defaultCoreCipherList and defaultCipherList:

node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
ECDHE-RSA-AES128-GCM-SHA256
!RC4 

defaultCoreCipherList 列表在编译时设置,defaultCipherList 在运行时设置。

¥i.e. the defaultCoreCipherList list is set at compilation time and the defaultCipherList is set at runtime.

要在运行时修改默认密码套件,请修改 tls.DEFAULT_CIPHERS 变量,这必须在监听任何套接字之前执行,它不会影响已经打开的套接字。例如:

¥To modify the default cipher suites from within the runtime, modify the tls.DEFAULT_CIPHERS variable, this must be performed before listening on any sockets, it will not affect sockets already opened. For example:

// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
tls.DEFAULT_CIPHERS +=
  ':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
  ':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
  ':!kRSA'; 

也可以使用 tls.createSecureContext() 中的 ciphers 选项在每个客户端或服务器的基础上替换默认值,该选项在 tls.createServer()tls.connect() 和创建新的 tls.TLSSocket 时也可用。

¥The default can also be replaced on a per client or server basis using the ciphers option from tls.createSecureContext(), which is also available in tls.createServer(), tls.connect(), and when creating new tls.TLSSockets.

密码列表可以包含 TLSv1.3 密码套件名称、以 'TLS_' 开头的名称以及 TLSv1.2 及以下密码套件的规范的混合。TLSv1.2 密码支持旧规范格式,请参阅 OpenSSL 密码列表格式 文档了解详细信息,但这些规范不适用于 TLSv1.3 密码。TLSv1.3 套件只能通过在密码列表中包含其全名来启用。例如,不能使用旧版 TLSv1.2 'EECDH''!EECDH' 规范启用或禁用它们。

¥The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones that start with 'TLS_', and specifications for TLSv1.2 and below cipher suites. The TLSv1.2 ciphers support a legacy specification format, consult the OpenSSL cipher list format documentation for details, but those specifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only be enabled by including their full name in the cipher list. They cannot, for example, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or '!EECDH' specification.

尽管 TLSv1.3 和 TLSv1.2 密码套件的相对顺序不同,但 TLSv1.3 协议比 TLSv1.2 安全得多,如果握监视明它受支持,并且如果有的话,总是会被选择而不是 TLSv1.2 TLSv1.3 密码套件已启用。

¥Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3 protocol is significantly more secure than TLSv1.2, and will always be chosen over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3 cipher suites are enabled.

Node.js 中包含的默认密码套件经过精心挑选,以反映当前的安全最佳实践和风险缓解。更改默认密码套件会对应用的安全性产生重大影响。只有在绝对必要时才应使用 --tls-cipher-list 开关和 ciphers 选项。

¥The default cipher suite included within Node.js has been carefully selected to reflect current security best practices and risk mitigation. Changing the default cipher suite can have a significant impact on the security of an application. The --tls-cipher-list switch and ciphers option should by used only if absolutely necessary.

默认密码套件更喜欢 Chrome 的 '现代密码学' 设置 的 GCM 密码,也更喜欢 ECDHE 和 DHE 密码以实现完美的前向保密,同时提供一些向后兼容性。

¥The default cipher suite prefers GCM ciphers for Chrome's 'modern cryptography' setting and also prefers ECDHE and DHE ciphers for perfect forward secrecy, while offering some backward compatibility.

依赖不安全且不推荐使用的 RC4 或基于 DES 的密码(如 Internet Explorer 6)的旧客户端无法使用默认配置完成握手过程。如果必须支持这些客户端,TLS 建议 可能会提供兼容的密码套件。有关格式的更多详细信息,请参阅 OpenSSL 密码列表格式 文档。

¥Old clients that rely on insecure and deprecated RC4 or DES-based ciphers (like Internet Explorer 6) cannot complete the handshaking process with the default configuration. If these clients must be supported, the TLS recommendations may offer a compatible cipher suite. For more details on the format, see the OpenSSL cipher list format documentation.

只有五个 TLSv1.3 密码套件:

¥There are only five TLSv1.3 cipher suites:

  • 'TLS_AES_256_GCM_SHA384'

  • 'TLS_CHACHA20_POLY1305_SHA256'

  • 'TLS_AES_128_GCM_SHA256'

  • 'TLS_AES_128_CCM_SHA256'

  • 'TLS_AES_128_CCM_8_SHA256'

默认启用前三个。TLSv1.3 支持这两个基于 CCM 的套件,因为它们在受限系统上的性能可能更高,但默认情况下未启用它们,因为它们提供的安全性较低。

¥The first three are enabled by default. The two CCM-based suites are supported by TLSv1.3 because they may be more performant on constrained systems, but they are not enabled by default since they offer less security.

X509 证书错误代码#

¥X509 certificate error codes

由于 OpenSSL 报告的证书错误,多个功能可能会失败。在这种情况下,该函数通过其回调提供 <Error>,该回调具有属性 code,该属性可以采用以下值之一:

¥Multiple functions can fail due to certificate errors that are reported by OpenSSL. In such a case, the function provides an <Error> via its callback that has the property code which can take one of the following values:

  • 'UNABLE_TO_GET_ISSUER_CERT':无法获得颁发者证书。

    ¥'UNABLE_TO_GET_ISSUER_CERT': Unable to get issuer certificate.

  • 'UNABLE_TO_GET_CRL':无法获得证书 CRL。

    ¥'UNABLE_TO_GET_CRL': Unable to get certificate CRL.

  • 'UNABLE_TO_DECRYPT_CERT_SIGNATURE':无法解密证书的签名。

    ¥'UNABLE_TO_DECRYPT_CERT_SIGNATURE': Unable to decrypt certificate's signature.

  • 'UNABLE_TO_DECRYPT_CRL_SIGNATURE':无法解密 CRL 的签名。

    ¥'UNABLE_TO_DECRYPT_CRL_SIGNATURE': Unable to decrypt CRL's signature.

  • 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY':无法解码发行者公钥。

    ¥'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY': Unable to decode issuer public key.

  • 'CERT_SIGNATURE_FAILURE':证书签名失败。

    ¥'CERT_SIGNATURE_FAILURE': Certificate signature failure.

  • 'CRL_SIGNATURE_FAILURE':CRL 签名失败。

    ¥'CRL_SIGNATURE_FAILURE': CRL signature failure.

  • 'CERT_NOT_YET_VALID':证书尚未生效。

    ¥'CERT_NOT_YET_VALID': Certificate is not yet valid.

  • 'CERT_HAS_EXPIRED':证书已过期。

    ¥'CERT_HAS_EXPIRED': Certificate has expired.

  • 'CRL_NOT_YET_VALID':CRL 尚未生效。

    ¥'CRL_NOT_YET_VALID': CRL is not yet valid.

  • 'CRL_HAS_EXPIRED':CRL 已过期。

    ¥'CRL_HAS_EXPIRED': CRL has expired.

  • 'ERROR_IN_CERT_NOT_BEFORE_FIELD':证书的 notBefore 字段中的格式错误。

    ¥'ERROR_IN_CERT_NOT_BEFORE_FIELD': Format error in certificate's notBefore field.

  • 'ERROR_IN_CERT_NOT_AFTER_FIELD':证书的 notAfter 字段中的格式错误。

    ¥'ERROR_IN_CERT_NOT_AFTER_FIELD': Format error in certificate's notAfter field.

  • 'ERROR_IN_CRL_LAST_UPDATE_FIELD':CRL 的 lastUpdate 字段中的格式错误。

    ¥'ERROR_IN_CRL_LAST_UPDATE_FIELD': Format error in CRL's lastUpdate field.

  • 'ERROR_IN_CRL_NEXT_UPDATE_FIELD':CRL 的 nextUpdate 字段中的格式错误。

    ¥'ERROR_IN_CRL_NEXT_UPDATE_FIELD': Format error in CRL's nextUpdate field.

  • 'OUT_OF_MEM':内存不足。

    ¥'OUT_OF_MEM': Out of memory.

  • 'DEPTH_ZERO_SELF_SIGNED_CERT':自签名证书。

    ¥'DEPTH_ZERO_SELF_SIGNED_CERT': Self signed certificate.

  • 'SELF_SIGNED_CERT_IN_CHAIN':证书链中的自签名证书。

    ¥'SELF_SIGNED_CERT_IN_CHAIN': Self signed certificate in certificate chain.

  • 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY':无法获得本地颁发者证书。

    ¥'UNABLE_TO_GET_ISSUER_CERT_LOCALLY': Unable to get local issuer certificate.

  • 'UNABLE_TO_VERIFY_LEAF_SIGNATURE':无法验证第一个证书。

    ¥'UNABLE_TO_VERIFY_LEAF_SIGNATURE': Unable to verify the first certificate.

  • 'CERT_CHAIN_TOO_LONG':证书链太长。

    ¥'CERT_CHAIN_TOO_LONG': Certificate chain too long.

  • 'CERT_REVOKED':证书已撤销。

    ¥'CERT_REVOKED': Certificate revoked.

  • 'INVALID_CA':无效的 CA 证书。

    ¥'INVALID_CA': Invalid CA certificate.

  • 'PATH_LENGTH_EXCEEDED':超出路径长度限制。

    ¥'PATH_LENGTH_EXCEEDED': Path length constraint exceeded.

  • 'INVALID_PURPOSE':不支持的证书用途。

    ¥'INVALID_PURPOSE': Unsupported certificate purpose.

  • 'CERT_UNTRUSTED':证书不受信任。

    ¥'CERT_UNTRUSTED': Certificate not trusted.

  • 'CERT_REJECTED':证书被拒绝。

    ¥'CERT_REJECTED': Certificate rejected.

  • 'HOSTNAME_MISMATCH':主机名不匹配。

    ¥'HOSTNAME_MISMATCH': Hostname mismatch.

类:tls.CryptoStream#

¥Class: tls.CryptoStream

稳定性: 0 - 已弃用:改用 tls.TLSSocket

¥Stability: 0 - Deprecated: Use tls.TLSSocket instead.

tls.CryptoStream 类表示加密数据流。此类已弃用,不应再使用。

¥The tls.CryptoStream class represents a stream of encrypted data. This class is deprecated and should no longer be used.

cryptoStream.bytesWritten#

cryptoStream.bytesWritten 属性返回写入底层套接字的总字节数,包括实现 TLS 协议所需的字节数。

¥The cryptoStream.bytesWritten property returns the total number of bytes written to the underlying socket including the bytes required for the implementation of the TLS protocol.

类:tls.SecurePair#

¥Class: tls.SecurePair

稳定性: 0 - 已弃用:改用 tls.TLSSocket

¥Stability: 0 - Deprecated: Use tls.TLSSocket instead.

tls.createSecurePair() 返回。

¥Returned by tls.createSecurePair().

事件:'secure'#

¥Event: 'secure'

一旦建立了安全连接,则 SecurePair 对象就会触发 'secure' 事件。

¥The 'secure' event is emitted by the SecurePair object once a secure connection has been established.

与检查服务器 'secureConnection' 事件一样,应检查 pair.cleartext.authorized 以确认所使用的证书是否已正确授权。

¥As with checking for the server 'secureConnection' event, pair.cleartext.authorized should be inspected to confirm whether the certificate used is properly authorized.

类:tls.Server#

¥Class: tls.Server

接受使用 TLS 或 SSL 的加密连接。

¥Accepts encrypted connections using TLS or SSL.

事件:'connection'#

¥Event: 'connection'

此事件在建立新的 TCP 流时触发,在 TLS 握手开始之前。socket 通常是 net.Socket 类型的对象,但不会像从 net.Server 'connection' 事件创建的套接字那样接收事件。通常用户不会想访问这个事件。

¥This event is emitted when a new TCP stream is established, before the TLS handshake begins. socket is typically an object of type net.Socket but will not receive events unlike the socket created from the net.Server 'connection' event. Usually users will not want to access this event.

此事件也可以由用户显式地触发以将连接注入 TLS 服务器。在这种情况下,任何 Duplex 流都可以通过。

¥This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any Duplex stream can be passed.

事件:'keylog'#

¥Event: 'keylog'

  • line <Buffer> ASCII 文本行,采用 NSS SSLKEYLOGFILE 格式。

    ¥line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.

  • tlsSocket <tls.TLSSocket> 生成它的 tls.TLSSocket 实例。

    ¥tlsSocket <tls.TLSSocket> The tls.TLSSocket instance on which it was generated.

keylog 事件在生成或通过与此服务器的连接接收密钥材料时触发(通常在握手完成之前,但不一定)。该密钥材料可以存储用于调试,因为它允许对捕获的 TLS 流量进行解密。它可以为每个套接字多次触发。

¥The keylog event is emitted when key material is generated or received by a connection to this server (typically before handshake has completed, but not necessarily). This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times for each socket.

一个典型的用例是将接收到的行附加到公共文本文件中,稍后软件(例如 Wireshark)使用它来解密流量:

¥A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:

const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
server.on('keylog', (line, tlsSocket) => {
  if (tlsSocket.remoteAddress !== '...')
    return; // Only log keys for a particular IP
  logFile.write(line);
}); 

事件:'newSession'#

¥Event: 'newSession'

在创建新的 TLS 会话时触发 'newSession' 事件。这可用于在外部存储中存储会话。数据应该提供给 'resumeSession' 回调。

¥The 'newSession' event is emitted upon creation of a new TLS session. This may be used to store sessions in external storage. The data should be provided to the 'resumeSession' callback.

监听器回调在调用时传入三个参数:

¥The listener callback is passed three arguments when called:

  • sessionId <Buffer> TLS 会话标识符

    ¥sessionId <Buffer> The TLS session identifier

  • sessionData <Buffer> TLS 会话数据

    ¥sessionData <Buffer> The TLS session data

  • callback <Function> 回调函数不带参数,必须调用这些参数才能通过安全连接发送或接收数据。

    ¥callback <Function> A callback function taking no arguments that must be invoked in order for data to be sent or received over the secure connection.

监听此事件只会对添加事件监听器后建立的连接有影响。

¥Listening for this event will have an effect only on connections established after the addition of the event listener.

事件:'OCSPRequest'#

¥Event: 'OCSPRequest'

当客户端发送证书状态请求时会触发 'OCSPRequest' 事件。监听器回调在调用时传入三个参数:

¥The 'OCSPRequest' event is emitted when the client sends a certificate status request. The listener callback is passed three arguments when called:

  • certificate <Buffer> 服务器证书

    ¥certificate <Buffer> The server certificate

  • issuer <Buffer> 发行人证书

    ¥issuer <Buffer> The issuer's certificate

  • callback <Function> 必须调用的回调函数来提供 OCSP 请求的结果。

    ¥callback <Function> A callback function that must be invoked to provide the results of the OCSP request.

可以解析服务器当前的证书,获取 OCSP URL 和证书 ID;在获得 OCSP 响应后,然后调用 callback(null, resp),其中 resp 是包含 OCSP 响应的 Buffer 实例。certificateissuer 都是主证书和颁发者证书的 Buffer DER 表示。这些可用于获取 OCSP 证书 ID 和 OCSP 端点 URL。

¥The server's current certificate can be parsed to obtain the OCSP URL and certificate ID; after obtaining an OCSP response, callback(null, resp) is then invoked, where resp is a Buffer instance containing the OCSP response. Both certificate and issuer are Buffer DER-representations of the primary and issuer's certificates. These can be used to obtain the OCSP certificate ID and OCSP endpoint URL.

或者,可以调用 callback(null, null),表示没有 OCSP 响应。

¥Alternatively, callback(null, null) may be called, indicating that there was no OCSP response.

调用 callback(err) 将导致调用 socket.destroy(err)

¥Calling callback(err) will result in a socket.destroy(err) call.

OCSP 请求的典型流程如下:

¥The typical flow of an OCSP request is as follows:

  1. 客户端连接到服务器并发送 'OCSPRequest'(通过 ClientHello 中的状态信息扩展)。

    ¥Client connects to the server and sends an 'OCSPRequest' (via the status info extension in ClientHello).

  2. 服务器收到请求并触发 'OCSPRequest' 事件,如果已注册则调用监听器。

    ¥Server receives the request and emits the 'OCSPRequest' event, calling the listener if registered.

  3. 服务器从 certificateissuer 中提取 OCSP URL,并向 CA 执行 OCSP 请求

    ¥Server extracts the OCSP URL from either the certificate or issuer and performs an OCSP request to the CA.

  4. 服务器从 CA 接收 'OCSPResponse' 并通过 callback 参数将其发送回客户端

    ¥Server receives 'OCSPResponse' from the CA and sends it back to the client via the callback argument

  5. 客户端验证响应并销毁套接字或执行握手。

    ¥Client validates the response and either destroys the socket or performs a handshake.

如果证书是自签名证书或颁发者不在根证书列表中,则 issuer 可以是 null。(在建立 TLS 连接时可以通过 ca 选项提供颁发者。)

¥The issuer can be null if the certificate is either self-signed or the issuer is not in the root certificates list. (An issuer may be provided via the ca option when establishing the TLS connection.)

监听此事件只会对添加事件监听器后建立的连接有影响。

¥Listening for this event will have an effect only on connections established after the addition of the event listener.

可以使用像 asn1.js 这样的 npm 模块来解析证书。

¥An npm module like asn1.js may be used to parse the certificates.

事件:'resumeSession'#

¥Event: 'resumeSession'

当客户端请求恢复之前的 TLS 会话时,则会触发 'resumeSession' 事件。监听器回调在调用时传入两个参数:

¥The 'resumeSession' event is emitted when the client requests to resume a previous TLS session. The listener callback is passed two arguments when called:

  • sessionId <Buffer> TLS 会话标识符

    ¥sessionId <Buffer> The TLS session identifier

  • callback <Function> 恢复先前会话时调用的回调函数:callback([err[, sessionData]])

    ¥callback <Function> A callback function to be called when the prior session has been recovered: callback([err[, sessionData]])

事件监听器应该使用给定的 sessionId 在外部存储中为 'newSession' 事件处理程序保存的 sessionData 执行查找。如果找到,则调用 callback(null, sessionData) 恢复会话。如果没有找到,则会话将无法恢复。callback() 必须在没有 sessionData 的情况下被调用,以便握手可以继续并可以创建新的会话。可以调用 callback(err) 来终止传入的连接并销毁套接字。

¥The event listener should perform a lookup in external storage for the sessionData saved by the 'newSession' event handler using the given sessionId. If found, call callback(null, sessionData) to resume the session. If not found, the session cannot be resumed. callback() must be called without sessionData so that the handshake can continue and a new session can be created. It is possible to call callback(err) to terminate the incoming connection and destroy the socket.

监听此事件只会对添加事件监听器后建立的连接有影响。

¥Listening for this event will have an effect only on connections established after the addition of the event listener.

以下说明恢复 TLS 会话:

¥The following illustrates resuming a TLS session:

const tlsSessionStore = {};
server.on('newSession', (id, data, cb) => {
  tlsSessionStore[id.toString('hex')] = data;
  cb();
});
server.on('resumeSession', (id, cb) => {
  cb(null, tlsSessionStore[id.toString('hex')] || null);
}); 

事件:'secureConnection'#

¥Event: 'secureConnection'

'secureConnection' 事件在新连接的握手过程成功完成后触发。监听器回调在调用时传入一个参数:

¥The 'secureConnection' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback is passed a single argument when called:

tlsSocket.authorized 属性是一个 boolean,指示客户端是否已通过服务器提供的证书颁发机构之一进行验证。如果 tlsSocket.authorizedfalse,则设置 socket.authorizationError 来描述授权失败的方式。根据 TLS 服务器的设置,可能仍会接受未经授权的连接。

¥The tlsSocket.authorized property is a boolean indicating whether the client has been verified by one of the supplied Certificate Authorities for the server. If tlsSocket.authorized is false, then socket.authorizationError is set to describe how authorization failed. Depending on the settings of the TLS server, unauthorized connections may still be accepted.

tlsSocket.alpnProtocol 属性是包含所选 ALPN 协议的字符串。当 ALPN 由于客户端或服务器未发送 ALPN 扩展而没有选择协议时,tlsSocket.alpnProtocol 等于 false

¥The tlsSocket.alpnProtocol property is a string that contains the selected ALPN protocol. When ALPN has no selected protocol because the client or the server did not send an ALPN extension, tlsSocket.alpnProtocol equals false.

tlsSocket.servername 属性是包含通过 SNI 请求的服务器名称的字符串。

¥The tlsSocket.servername property is a string containing the server name requested via SNI.

事件:'tlsClientError'#

¥Event: 'tlsClientError'

在建立安全连接之前发生错误时会触发 'tlsClientError' 事件。监听器回调在调用时传入两个参数:

¥The 'tlsClientError' event is emitted when an error occurs before a secure connection is established. The listener callback is passed two arguments when called:

  • exception <Error> 描述错误的 Error 对象

    ¥exception <Error> The Error object describing the error

  • tlsSocket <tls.TLSSocket> 错误源自的 tls.TLSSocket 实例。

    ¥tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the error originated.

server.addContext(hostname, context)#

server.addContext() 方法添加了安全的上下文,如果客户端请求的 SNI 名称与提供的 hostname(或通配符)匹配,则将使用该上下文。

¥The server.addContext() method adds a secure context that will be used if the client request's SNI name matches the supplied hostname (or wildcard).

当有多个匹配的上下文时,使用最近添加的一个。

¥When there are multiple matching contexts, the most recently added one is used.

server.address()#

返回操作系统报告的绑定地址、地址族名称和服务器端口。有关详细信息,请参阅 net.Server.address()

¥Returns the bound address, the address family name, and port of the server as reported by the operating system. See net.Server.address() for more information.

server.close([callback])#

  • callback <Function> 监听器回调,将被注册以监听服务器实例的 'close' 事件。

    ¥callback <Function> A listener callback that will be registered to listen for the server instance's 'close' event.

  • 返回:<tls.Server>

    ¥Returns: <tls.Server>

server.close() 方法阻止服务器接受新连接。

¥The server.close() method stops the server from accepting new connections.

此函数异步地运行。当服务器没有更多打开的连接时,则将触发 'close' 事件。

¥This function operates asynchronously. The 'close' event will be emitted when the server has no more open connections.

server.getTicketKeys()#

  • 返回:<Buffer> 包含会话票证密钥的 48 字节缓冲区。

    ¥Returns: <Buffer> A 48-byte buffer containing the session ticket keys.

返回会话票证密钥。

¥Returns the session ticket keys.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

server.listen()#

启动服务器监听加密连接。此方法与 net.Server 中的 server.listen() 相同。

¥Starts the server listening for encrypted connections. This method is identical to server.listen() from net.Server.

server.setSecureContext(options)#

server.setSecureContext() 方法替换现有服务器的安全上下文。与服务器的现有连接不会中断。

¥The server.setSecureContext() method replaces the secure context of an existing server. Existing connections to the server are not interrupted.

server.setTicketKeys(keys)#

设置会话票证密钥。

¥Sets the session ticket keys.

更改票证密钥仅对以后的服务器连接有效。现有的或当前挂起的服务器连接将使用以前的键。

¥Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

类:tls.TLSSocket#

¥Class: tls.TLSSocket

对写入的数据和所有必需的 TLS 协商进行透明加密。

¥Performs transparent encryption of written data and all required TLS negotiation.

tls.TLSSocket 的实例实现双工 接口。

¥Instances of tls.TLSSocket implement the duplex Stream interface.

返回 TLS 连接元数据的方法(例如 tls.TLSSocket.getPeerCertificate())只会在连接打开时返回数据。

¥Methods that return TLS connection metadata (e.g. tls.TLSSocket.getPeerCertificate()) will only return data while the connection is open.

new tls.TLSSocket(socket[, options])#

  • socket <net.Socket> | <stream.Duplex> 在服务器端,任何 Duplex 流。在客户端,任何 net.Socket 实例(对于客户端的通用 Duplex 流支持,必须使用 tls.connect())。

    ¥socket <net.Socket> | <stream.Duplex> On the server side, any Duplex stream. On the client side, any instance of net.Socket (for generic Duplex stream support on the client side, tls.connect() must be used).

  • options <Object>

    • enableTrace:参见 tls.createServer()

      ¥enableTrace: See tls.createServer()

    • isServer:SSL/TLS 协议是不对称的,TLSSockets 必须知道它们是作为服务器还是客户端运行。如果 true TLS 套接字将被实例化为服务器。默认值:false

      ¥isServer: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If true the TLS socket will be instantiated as a server. Default: false.

    • server <net.Server> net.Server 实例。

      ¥server <net.Server> A net.Server instance.

    • requestCert:是否通过请求证书来验证远程对等体。客户端总是请求服务器证书。服务器(isServer 为真)可以将 requestCert 设置为真以请求客户端证书。

      ¥requestCert: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (isServer is true) may set requestCert to true to request a client certificate.

    • rejectUnauthorized:参见 tls.createServer()

      ¥rejectUnauthorized: See tls.createServer()

    • ALPNProtocols:参见 tls.createServer()

      ¥ALPNProtocols: See tls.createServer()

    • SNICallback:参见 tls.createServer()

      ¥SNICallback: See tls.createServer()

    • session <Buffer> 包含 TLS 会话的 Buffer 实例。

      ¥session <Buffer> A Buffer instance containing a TLS session.

    • requestOCSP <boolean> 如果为 true, 则指定将 OCSP 状态请求扩展添加到客户端 hello 并在建立安全通信之前在套接字上触发 'OCSPResponse' 事件

      ¥requestOCSP <boolean> If true, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication

    • secureContext:使用 tls.createSecureContext() 创建的 TLS 上下文对象。如果未提供 secureContext,则会通过将整个 options 对象传递给 tls.createSecureContext() 来创建一个。

      ¥secureContext: TLS context object created with tls.createSecureContext(). If a secureContext is not provided, one will be created by passing the entire options object to tls.createSecureContext().

    • ...:如果缺少 secureContext 选项,则使用 tls.createSecureContext() 选项。否则,它们将被忽略。

      ¥...: tls.createSecureContext() options that are used if the secureContext option is missing. Otherwise, they are ignored.

从现有的 TCP 套接字构造新的 tls.TLSSocket 对象。

¥Construct a new tls.TLSSocket object from an existing TCP socket.

事件:'keylog'#

¥Event: 'keylog'

  • line <Buffer> ASCII 文本行,采用 NSS SSLKEYLOGFILE 格式。

    ¥line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.

当套接字生成或接收密钥材料时,keylog 事件在 tls.TLSSocket 上触发。该密钥材料可以存储用于调试,因为它允许对捕获的 TLS 流量进行解密。它可能会在握手完成之前或之后多次触发。

¥The keylog event is emitted on a tls.TLSSocket when key material is generated or received by the socket. This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times, before or after the handshake completes.

一个典型的用例是将接收到的行附加到公共文本文件中,稍后软件(例如 Wireshark)使用它来解密流量:

¥A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:

const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
tlsSocket.on('keylog', (line) => logFile.write(line)); 

事件:'OCSPResponse'#

¥Event: 'OCSPResponse'

如果在创建 tls.TLSSocket 并收到 OCSP 响应时设置了 requestOCSP 选项,则会触发 'OCSPResponse' 事件。监听器回调在调用时传入一个参数:

¥The 'OCSPResponse' event is emitted if the requestOCSP option was set when the tls.TLSSocket was created and an OCSP response has been received. The listener callback is passed a single argument when called:

  • response <Buffer> 服务器的 OCSP 响应

    ¥response <Buffer> The server's OCSP response

通常,response 是来自服务器 CA 的数字签名对象,其中包含有关服务器证书吊销状态的信息。

¥Typically, the response is a digitally signed object from the server's CA that contains information about server's certificate revocation status.

事件:'secureConnect'#

¥Event: 'secureConnect'

'secureConnect' 事件在新连接的握手过程成功完成后触发。无论服务器的证书是否被授权,都会调用监听回调。客户端有责任检查 tlsSocket.authorized 属性以确定服务器证书是否由指定的 CA 之一签名。如果为 tlsSocket.authorized === false,则可以通过检查 tlsSocket.authorizationError 属性来发现错误。如果使用了 ALPN,可以检查 tlsSocket.alpnProtocol 属性来确定协商的协议。

¥The 'secureConnect' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback will be called regardless of whether or not the server's certificate has been authorized. It is the client's responsibility to check the tlsSocket.authorized property to determine if the server certificate was signed by one of the specified CAs. If tlsSocket.authorized === false, then the error can be found by examining the tlsSocket.authorizationError property. If ALPN was used, the tlsSocket.alpnProtocol property can be checked to determine the negotiated protocol.

当使用 new tls.TLSSocket() 构造函数创建 <tls.TLSSocket> 时,则不会触发 'secureConnect' 事件。

¥The 'secureConnect' event is not emitted when a <tls.TLSSocket> is created using the new tls.TLSSocket() constructor.

事件:'session'#

¥Event: 'session'

当新会话或 TLS 票证可用时,则客户端 tls.TLSSocket 上会触发 'session' 事件。这可能会也可能不会在握手完成之前发生,具体取决于协商的 TLS 协议版本。该事件未在服务器上触发,或者未创建新会话,例如,当连接恢复时。对于某些 TLS 协议版本,事件可能会多次触发,在这种情况下,所有会话都可以用于恢复。

¥The 'session' event is emitted on a client tls.TLSSocket when a new session or TLS ticket is available. This may or may not be before the handshake is complete, depending on the TLS protocol version that was negotiated. The event is not emitted on the server, or if a new session was not created, for example, when the connection was resumed. For some TLS protocol versions the event may be emitted multiple times, in which case all the sessions can be used for resumption.

在客户端,可以将 session 提供给 tls.connect()session 选项来恢复连接。

¥On the client, the session can be provided to the session option of tls.connect() to resume the connection.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

对于 TLSv1.2 及以下版本,握手完成后可以调用 tls.TLSSocket.getSession()。对于 TLSv1.3,协议只允许基于票证的恢复,发送多张票证,直到握手完成后才发送票证。所以需要等待 'session' 事件才能得到可恢复的会话。应用应该使用 'session' 事件而不是 getSession() 来确保它们适用于所有 TLS 版本。只希望获得或使用一个会话的应用应该只监听此事件一次:

¥For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed by the protocol, multiple tickets are sent, and the tickets aren't sent until after the handshake completes. So it is necessary to wait for the 'session' event to get a resumable session. Applications should use the 'session' event instead of getSession() to ensure they will work for all TLS versions. Applications that only expect to get or use one session should listen for this event only once:

tlsSocket.once('session', (session) => {
  // The session can be used immediately or later.
  tls.connect({
    session: session,
    // Other connect options...
  });
}); 

tlsSocket.address()#

返回操作系统报告的底层套接字的绑定 address、地址 family 名称和 port{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

¥Returns the bound address, the address family name, and port of the underlying socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

tlsSocket.authorizationError#

返回未验证对等方证书的原因。此属性仅在 tlsSocket.authorized === false 时设置。

¥Returns the reason why the peer's certificate was not been verified. This property is set only when tlsSocket.authorized === false.

tlsSocket.authorized#

如果对等证书由创建 tls.TLSSocket 实例时指定的 CA 之一签名,则此属性为 true,否则为 false

¥This property is true if the peer certificate was signed by one of the CAs specified when creating the tls.TLSSocket instance, otherwise false.

tlsSocket.disableRenegotiation()#

禁用此 TLSSocket 实例的 TLS 重新协商。一旦调用,则尝试重新协商将在 TLSSocket 上触发 'error' 事件。

¥Disables TLS renegotiation for this TLSSocket instance. Once called, attempts to renegotiate will trigger an 'error' event on the TLSSocket.

tlsSocket.enableTrace()#

当启用后,TLS 数据包跟踪信息将写入 stderr。这可用于调试 TLS 连接问题。

¥When enabled, TLS packet trace information is written to stderr. This can be used to debug TLS connection problems.

输出的格式与 openssl s_client -traceopenssl s_server -trace 的输出相同。虽然它是由 OpenSSL 的 SSL_trace() 函数生成的,但格式未记录,可以在不通知的情况下更改,不应依赖。

¥The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's SSL_trace() function, the format is undocumented, can change without notice, and should not be relied on.

tlsSocket.encrypted#

总是返回 true。这可用于将 TLS 套接字与常规 net.Socket 实例区分开来。

¥Always returns true. This may be used to distinguish TLS sockets from regular net.Socket instances.

tlsSocket.exportKeyingMaterial(length, label[, context])#

密钥材料用于验证以防止网络协议中的不同类型的攻击,例如在 IEEE 802.1X 的规范中。

¥Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.

示例

¥Example

const keyingMaterial = tlsSocket.exportKeyingMaterial(
  128,
  'client finished');

/*
 Example return value of keyingMaterial:
 <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
    74 ef 2c ... 78 more bytes>
*/ 

有关详细信息,请参阅 OpenSSL SSL_export_keying_material 文档。

¥See the OpenSSL SSL_export_keying_material documentation for more information.

tlsSocket.getCertificate()#

返回表示本地证书的对象。返回的对象有一些与证书字段对应的属性。

¥Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

有关证书结构的示例,请参见 tls.TLSSocket.getPeerCertificate()

¥See tls.TLSSocket.getPeerCertificate() for an example of the certificate structure.

如果没有本地证书,则将返回空对象。如果套接字被销毁,则返回 null

¥If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

tlsSocket.getCipher()#

返回包含协商密码套件信息的对象。

¥Returns an object containing information on the negotiated cipher suite.

例如,带有 AES256-SHA 密码的 TLSv1.2 协议:

¥For example, a TLSv1.2 protocol with AES256-SHA cipher:

{
    "name": "AES256-SHA",
    "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
    "version": "SSLv3"
} 

有关详细信息,请参阅 SSL_CIPHER_get_name

¥See SSL_CIPHER_get_name for more information.

tlsSocket.getEphemeralKeyInfo()#

返回一个对象,表示客户端连接上 完全前向保密 中临时密钥交换的参数的类型、名称和大小。当密钥交换不是短暂的时,则它返回空对象。因为这仅在客户端套接字上受支持;如果在服务器套接字上调用,则返回 null。支持的类型是 'DH''ECDH'name 属性仅在类型为 'ECDH' 时可用。

¥Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. The name property is available only when type is 'ECDH'.

例如:{ type: 'ECDH', name: 'prime256v1', size: 256 }

¥For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

tlsSocket.getFinished()#

  • 返回:<Buffer> | <undefined> 作为 SSL/TLS 握手的一部分已发送到套接字的最新 Finished 消息,如果尚未发送 Finished 消息,则为 undefined

    ¥Returns: <Buffer> | <undefined> The latest Finished message that has been sent to the socket as part of a SSL/TLS handshake, or undefined if no Finished message has been sent yet.

由于 Finished 消息是完整握手的消息摘要(对于 TLS 1.0 总共有 192 位,对于 SSL 3.0 则更多),当不需要或不需要 SSL/TLS 提供的身份验证时,它们可用于外部身份验证程序不够。

¥As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

对应 OpenSSL 中的 SSL_get_finished 例程,可用于实现 RFC 5929tls-unique 通道绑定。

¥Corresponds to the SSL_get_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.

tlsSocket.getPeerCertificate([detailed])#

  • detailed <boolean> 如果为 true,则包含完整的证书链,否则仅包含对等方的证书。

    ¥detailed <boolean> Include the full certificate chain if true, otherwise include just the peer's certificate.

  • 返回:<Object> 证书对象。

    ¥Returns: <Object> A certificate object.

返回代表对等方证书的对象。如果对端没有提供证书,则将返回空对象。如果套接字被销毁,则返回 null

¥Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

如果请求完整的证书链,则每个证书都将包含一个 issuerCertificate 属性,其中包含代表其颁发者证书的对象。

¥If the full certificate chain was requested, each certificate will include an issuerCertificate property containing an object representing its issuer's certificate.

证书对象#

¥Certificate object

证书对象具有与证书字段对应的属性。

¥A certificate object has properties corresponding to the fields of the certificate.

  • ca <boolean> 如果是证书颁发机构 (CA),则为 true,否则为 false

    ¥ca <boolean> true if a Certificate Authority (CA), false otherwise.

  • raw <Buffer> DER 编码的 X.509 证书数据。

    ¥raw <Buffer> The DER encoded X.509 certificate data.

  • subject <Object> 证书主题,按照国家 (C)、州或省 (ST)、地区 (L)、组织 (O)、组织单位 (OU) 和通用名称 (CN) 进行描述。CommonName 通常是带有 TLS 证书的 DNS 名称。示例:{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}

    ¥subject <Object> The certificate subject, described in terms of Country (C), StateOrProvince (ST), Locality (L), Organization (O), OrganizationalUnit (OU), and CommonName (CN). The CommonName is typically a DNS name with TLS certificates. Example: {C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.

  • issuer <Object> 证书颁发者,使用与 subject 相同的术语描述。

    ¥issuer <Object> The certificate issuer, described in the same terms as the subject.

  • valid_from <string> 证书有效的开始日期时间。

    ¥valid_from <string> The date-time the certificate is valid from.

  • valid_to <string> 证书有效的结束日期时间。

    ¥valid_to <string> The date-time the certificate is valid to.

  • serialNumber <string> 证书序列号,以十六进制字符串表示。示例:'B9B0D332A1AA5635'

    ¥serialNumber <string> The certificate serial number, as a hex string. Example: 'B9B0D332A1AA5635'.

  • fingerprint <string> DER 编码证书的 SHA-1 摘要。它作为 : 分隔的十六进制字符串返回。示例:'2A:7A:C2:DD:...'

    ¥fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.

  • fingerprint256 <string> DER 编码证书的 SHA-256 摘要。它作为 : 分隔的十六进制字符串返回。示例:'2A:7A:C2:DD:...'

    ¥fingerprint256 <string> The SHA-256 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.

  • fingerprint512 <string> DER 编码证书的 SHA-512 摘要。它作为 : 分隔的十六进制字符串返回。示例:'2A:7A:C2:DD:...'

    ¥fingerprint512 <string> The SHA-512 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.

  • ext_key_usage <Array> (可选的)扩展密钥用法,一组 OID。

    ¥ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.

  • subjectaltname <string> (可选的)包含主题的串联名称的字符串,是 subject 名称的替代方案。

    ¥subjectaltname <string> (Optional) A string containing concatenated names for the subject, an alternative to the subject names.

  • infoAccess <Array> (可选的)描述 AuthorityInfoAccess 的数组,与 OCSP 一起使用。

    ¥infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess, used with OCSP.

  • issuerCertificate <Object> (可选的)颁发者证书对象。对于自签名证书,这可能是一个循环引用。

    ¥issuerCertificate <Object> (Optional) The issuer certificate object. For self-signed certificates, this may be a circular reference.

证书可能包含有关公钥的信息,具体取决于密钥类型。

¥The certificate may contain information about the public key, depending on the key type.

对于 RSA 密钥,可以定义以下属性:

¥For RSA keys, the following properties may be defined:

  • bits <number> RSA 位大小。示例:1024

    ¥bits <number> The RSA bit size. Example: 1024.

  • exponent <string> RSA 指数,作为十六进制数字表示法的字符串。示例:'0x010001'

    ¥exponent <string> The RSA exponent, as a string in hexadecimal number notation. Example: '0x010001'.

  • modulus <string> RSA 模数,作为十六进制字符串。示例:'B56CE45CB7...'

    ¥modulus <string> The RSA modulus, as a hexadecimal string. Example: 'B56CE45CB7...'.

  • pubkey <Buffer> 公钥。

    ¥pubkey <Buffer> The public key.

对于 EC 密钥,可以定义以下属性:

¥For EC keys, the following properties may be defined:

  • pubkey <Buffer> 公钥。

    ¥pubkey <Buffer> The public key.

  • bits <number> 密钥大小(以位为单位)。示例:256

    ¥bits <number> The key size in bits. Example: 256.

  • asn1Curve <string> (可选的)椭圆曲线 OID 的 ASN.1 名称。知名曲线由 OID 标识。虽然这很不寻常,但曲线可能是由其数学属性标识的,在这种情况下,它不会有 OID。示例:'prime256v1'

    ¥asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic curve. Well-known curves are identified by an OID. While it is unusual, it is possible that the curve is identified by its mathematical properties, in which case it will not have an OID. Example: 'prime256v1'.

  • nistCurve <string> (可选的)椭圆曲线的 NIST 名称(如果有的话)(并非所有众所周知的曲线都已由 NIST 指定名称)。示例:'P-256'

    ¥nistCurve <string> (Optional) The NIST name for the elliptic curve, if it has one (not all well-known curves have been assigned names by NIST). Example: 'P-256'.

示例证书:

¥Example certificate:

{ subject:
   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
     CN: '*.nodejs.org' },
  issuer:
   { C: 'GB',
     ST: 'Greater Manchester',
     L: 'Salford',
     O: 'COMODO CA Limited',
     CN: 'COMODO RSA Domain Validation Secure Server CA' },
  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
  infoAccess:
   { 'CA Issuers - URI':
      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
  exponent: '0x10001',
  pubkey: <Buffer ... >,
  valid_from: 'Aug 14 00:00:00 2017 GMT',
  valid_to: 'Nov 20 23:59:59 2019 GMT',
  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
  fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32',
  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
  serialNumber: '66593D57F20CBC573E433381B5FEC280',
  raw: <Buffer ... > } 

tlsSocket.getPeerFinished()#

  • 返回:<Buffer> | <undefined> 作为 SSL/TLS 握手的一部分,预期或实际已从套接字接收到的最新 Finished 消息,如果到目前为止还没有 Finished 消息,则为 undefined

    ¥Returns: <Buffer> | <undefined> The latest Finished message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or undefined if there is no Finished message so far.

由于 Finished 消息是完整握手的消息摘要(对于 TLS 1.0 总共有 192 位,对于 SSL 3.0 则更多),当不需要或不需要 SSL/TLS 提供的身份验证时,它们可用于外部身份验证程序不够。

¥As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

对应 OpenSSL 中的 SSL_get_peer_finished 例程,可用于实现 RFC 5929tls-unique 通道绑定。

¥Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.

tlsSocket.getPeerX509Certificate()#

返回对等证书作为 <X509Certificate> 对象。

¥Returns the peer certificate as an <X509Certificate> object.

如果没有对等证书,或者套接字被销毁,则返回 undefined

¥If there is no peer certificate, or the socket has been destroyed, undefined will be returned.

tlsSocket.getProtocol()#

返回包含当前连接的协商 SSL/TLS 协议版本的字符串。对于尚未完成握手过程的已连接套接字,将返回值 'unknown'。服务器套接字或断开的客户端套接字将返回值 null

¥Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.

协议版本为:

¥Protocol versions are:

  • 'SSLv3'

  • 'TLSv1'

  • 'TLSv1.1'

  • 'TLSv1.2'

  • 'TLSv1.3'

有关详细信息,请参阅 OpenSSL SSL_get_version 文档。

¥See the OpenSSL SSL_get_version documentation for more information.

tlsSocket.getSession()#

如果没有协商会话,则返回 TLS 会话数据或 undefined。在客户端,可以将数据提供给 tls.connect()session 选项来恢复连接。在服务器上,它可能对调试有用。

¥Returns the TLS session data or undefined if no session was negotiated. On the client, the data can be provided to the session option of tls.connect() to resume the connection. On the server, it may be useful for debugging.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

注意:getSession() 仅适用于 TLSv1.2 及以下版本。对于 TLSv1.3,应用必须使用 'session' 事件(它也适用于 TLSv1.2 及更低版本)。

¥Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications must use the 'session' event (it also works for TLSv1.2 and below).

tlsSocket.getSharedSigalgs()#

  • 返回:<Array> 服务器和客户端之间共享的签名算法列表,按优先级降序排列。

    ¥Returns: <Array> List of signature algorithms shared between the server and the client in the order of decreasing preference.

有关详细信息,请参阅 SSL_get_shared_sigalgs

¥See SSL_get_shared_sigalgs for more information.

tlsSocket.getTLSTicket()#

对于客户端,如果可用,则返回 TLS 会话票证,或 undefined。对于服务器,总是返回 undefined

¥For a client, returns the TLS session ticket if one is available, or undefined. For a server, always returns undefined.

它可能对调试有用。

¥It may be useful for debugging.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

tlsSocket.getX509Certificate()#

将本地证书作为 <X509Certificate> 对象返回。

¥Returns the local certificate as an <X509Certificate> object.

如果没有本地证书,或者套接字被销毁,则返回 undefined

¥If there is no local certificate, or the socket has been destroyed, undefined will be returned.

tlsSocket.isSessionReused()#

  • 返回:<boolean> 如果会话被重用则为 true,否则为 false

    ¥Returns: <boolean> true if the session was reused, false otherwise.

有关详细信息,请参阅 会话恢复

¥See Session Resumption for more information.

tlsSocket.localAddress#

返回本地 IP 地址的字符串表示形式。

¥Returns the string representation of the local IP address.

tlsSocket.localPort#

返回本地端口的数字表示。

¥Returns the numeric representation of the local port.

tlsSocket.remoteAddress#

返回远程 IP 地址的字符串表示形式。例如,'74.125.127.100''2001:4860:a005::68'

¥Returns the string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

tlsSocket.remoteFamily#

返回远程 IP 族的字符串表示形式。'IPv4''IPv6'

¥Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

tlsSocket.remotePort#

返回远程端口的数字表示。例如,443

¥Returns the numeric representation of the remote port. For example, 443.

tlsSocket.renegotiate(options, callback)#

  • options <Object>

    • rejectUnauthorized <boolean> 如果不是 false,则服务器证书将根据提供的 CA 列表进行验证。如果验证失败,则触发 'error' 事件;err.code 包含 OpenSSL 错误代码。默认值:true

      ¥rejectUnauthorized <boolean> If not false, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails; err.code contains the OpenSSL error code. Default: true.

    • requestCert

  • callback <Function> 如果 renegotiate() 返回 true,则回调将绑定到 'secure' 事件。如果 renegotiate() 返回 false, 则 callback 将在下一个滴答中被调用并出错, 除非 tlsSocket 已被销毁, 在这种情况下根本不会调用 callback

    ¥callback <Function> If renegotiate() returned true, callback is attached once to the 'secure' event. If renegotiate() returned false, callback will be called in the next tick with an error, unless the tlsSocket has been destroyed, in which case callback will not be called at all.

  • 返回:<boolean> 如果启动重新协商则为 true,否则为 false

    ¥Returns: <boolean> true if renegotiation was initiated, false otherwise.

tlsSocket.renegotiate() 方法启动 TLS 重新协商过程。当完成后,callback 函数将传入一个参数,该参数是 Error(如果请求失败)或 null

¥The tlsSocket.renegotiate() method initiates a TLS renegotiation process. Upon completion, the callback function will be passed a single argument that is either an Error (if the request failed) or null.

此方法可用于在建立安全连接后请求对等方的证书。

¥This method can be used to request a peer's certificate after the secure connection has been established.

当作为服务器运行时,套接字将在 handshakeTimeout 超时后销毁并出现错误。

¥When running as the server, the socket will be destroyed with an error after handshakeTimeout timeout.

对于 TLSv1.3,无法发起重协商,协议不支持。

¥For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol.

tlsSocket.setKeyCert(context)#

tlsSocket.setKeyCert() 方法设置用于套接字的私钥和证书。如果你希望从 TLS 服务器的 ALPNCallback 中选择服务器证书,这主要很有用。

¥The tlsSocket.setKeyCert() method sets the private key and certificate to use for the socket. This is mainly useful if you wish to select a server certificate from a TLS server's ALPNCallback.

tlsSocket.setMaxSendFragment(size)#

  • size <number> 最大 TLS 片段大小。最大值为 16384。默认值:16384

    ¥size <number> The maximum TLS fragment size. The maximum value is 16384. Default: 16384.

  • 返回:<boolean>

    ¥Returns: <boolean>

tlsSocket.setMaxSendFragment() 方法设置最大 TLS 片段大小。设置限制成功返回 truefalse 否则。

¥The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.

较小的片段大小会减少客户端的缓冲延迟:较大的片段由 TLS 层缓冲,直到接收到整个片段并验证其完整性;大片段可以跨越多个往返,并且由于数据包丢失或重新排序,它们的处理可能会延迟。但是,较小的片段会增加额外的 TLS 成帧字节和 CPU 开销,这可能会降低整体服务器吞吐量。

¥Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.

tls.checkServerIdentity(hostname, cert)#

验证证书 cert 颁发给 hostname

¥Verifies the certificate cert is issued to hostname.

返回 <Error> 对象,失败时用 reasonhostcert 填充它。当成功时,返回 <undefined>

¥Returns <Error> object, populating it with reason, host, and cert on failure. On success, returns <undefined>.

此函数旨在与可以传递给 tls.connect()checkServerIdentity 选项结合使用,因此在 证书对象 上运行。出于其他目的,则考虑使用 x509.checkHost()

¥This function is intended to be used in combination with the checkServerIdentity option that can be passed to tls.connect() and as such operates on a certificate object. For other purposes, consider using x509.checkHost() instead.

此函数可以通过提供替代函数作为传给 tls.connect()options.checkServerIdentity 选项来覆盖。覆盖函数当然可以调用 tls.checkServerIdentity(),以增加通过额外验证完成的检查。

¥This function can be overwritten by providing an alternative function as the options.checkServerIdentity option that is passed to tls.connect(). The overwriting function can call tls.checkServerIdentity() of course, to augment the checks done with additional verification.

此函数仅在证书通过所有其他检查时才会调用,例如由受信任的 CA (options.ca) 颁发。

¥This function is only called if the certificate passed all other checks, such as being issued by trusted CA (options.ca).

如果存在匹配的 uniformResourceIdentifier 主题备用名称(请参阅 CVE-2021-44531),早期版本的 Node.js 会错误地接受给定 hostname 的证书。希望接受 uniformResourceIdentifier 主题替代名称的应用可以使用实现所需行为的自定义 options.checkServerIdentity 函数。

¥Earlier versions of Node.js incorrectly accepted certificates for a given hostname if a matching uniformResourceIdentifier subject alternative name was present (see CVE-2021-44531). Applications that wish to accept uniformResourceIdentifier subject alternative names can use a custom options.checkServerIdentity function that implements the desired behavior.

tls.connect(options[, callback])#

  • options <Object>

    • enableTrace:参见 tls.createServer()

      ¥enableTrace: See tls.createServer()

    • host <string> 客户端应该连接到的主机。默认值:'localhost'

      ¥host <string> Host the client should connect to. Default: 'localhost'.

    • port <number> 客户端应该连接到的端口。

      ¥port <number> Port the client should connect to.

    • path <string> 创建到路径的 Unix 套接字连接。如果指定了此选项,则 hostport 将被忽略。

      ¥path <string> Creates Unix socket connection to path. If this option is specified, host and port are ignored.

    • socket <stream.Duplex> 在给定的套接字上建立安全连接而不是创建新的套接字。通常,这是 net.Socket 的实例,但允许任何 Duplex 流。如果指定此选项,则忽略 pathhostport,证书验证除外。通常,套接字在传给 tls.connect() 的时候就已经连接上了,但是可以稍后再连接。socket 的连接/断开/销毁由用户负责;调用 tls.connect() 不会导致调用 net.connect()

      ¥socket <stream.Duplex> Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of net.Socket, but any Duplex stream is allowed. If this option is specified, path, host, and port are ignored, except for certificate validation. Usually, a socket is already connected when passed to tls.connect(), but it can be connected later. Connection/disconnection/destruction of socket is the user's responsibility; calling tls.connect() will not cause net.connect() to be called.

    • allowHalfOpen <boolean> 如果设置为 false,则当可读端结束时,套接字将自动结束可写端。如果设置了 socket 选项,则该选项无效。详见 net.SocketallowHalfOpen 选项。默认值:false

      ¥allowHalfOpen <boolean> If set to false, then the socket will automatically end the writable side when the readable side ends. If the socket option is set, this option has no effect. See the allowHalfOpen option of net.Socket for details. Default: false.

    • rejectUnauthorized <boolean> 如果不是 false,则服务器证书将根据提供的 CA 列表进行验证。如果验证失败,则触发 'error' 事件;err.code 包含 OpenSSL 错误代码。默认值:true

      ¥rejectUnauthorized <boolean> If not false, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails; err.code contains the OpenSSL error code. Default: true.

    • pskCallback <Function> 对于 TLS-PSK 协商,请参阅 预共享密钥

      ¥pskCallback <Function> For TLS-PSK negotiation, see Pre-shared keys.

    • ALPNProtocols<string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 包含支持的 ALPN 协议的字符串数组 BufferTypedArrayDataView,或单个 BufferTypedArrayDataViewBuffer 应采用 [len][name][len][name]... 格式,例如 '\x08http/1.1\x08http/1.0',其中 len 字节是下一个协议名的长度。传入数组通常要简单得多,例如 ['http/1.1', 'http/1.0']。列表中较早的协议比后面的有更高的优先级。

      ¥ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings, Buffers, TypedArrays, or DataViews, or a single Buffer, TypedArray, or DataView containing the supported ALPN protocols. Buffers should have the format [len][name][len][name]... e.g. '\x08http/1.1\x08http/1.0', where the len byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['http/1.1', 'http/1.0']. Protocols earlier in the list have higher preference than those later.

    • servername<string> SNI(服务器名称指示)TLS 扩展的服务器名称。它是所连接主机的名称,必须是主机名,而不是 IP 地址。它可以被多宿主服务器用来选择正确的证书展示给客户端,参见 SNICallback 选项到 tls.createServer()

      ¥servername: <string> Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the SNICallback option to tls.createServer().

    • checkServerIdentity(servername, cert) <Function> 根据证书检查服务器的主机名(或显式设置时提供的 servername)时要使用的回调函数(而不是内置的 tls.checkServerIdentity() 函数)。如果验证失败,则这应该返回 <Error>。如果验证了 servernamecert,则该方法应该返回 undefined

      ¥checkServerIdentity(servername, cert) <Function> A callback function to be used (instead of the builtin tls.checkServerIdentity() function) when checking the server's host name (or the provided servername when explicitly set) against the certificate. This should return an <Error> if verification fails. The method should return undefined if the servername and cert are verified.

    • session <Buffer> Buffer 实例,包含 TLS 会话。

      ¥session <Buffer> A Buffer instance, containing TLS session.

    • minDHSize <number> 接受 TLS 连接的 DH 参数的最小大小(以位为单位)。当服务器提供大小小于 minDHSize 的 DH 参数时,则 TLS 连接被销毁并抛出错误。默认值:1024

      ¥minDHSize <number> Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than minDHSize, the TLS connection is destroyed and an error is thrown. Default: 1024.

    • highWaterMark<number> 与可读流 highWaterMark 参数一致。默认值:16 * 1024

      ¥highWaterMark: <number> Consistent with the readable stream highWaterMark parameter. Default: 16 * 1024.

    • secureContext:使用 tls.createSecureContext() 创建的 TLS 上下文对象。如果未提供 secureContext,则会通过将整个 options 对象传递给 tls.createSecureContext() 来创建一个。

      ¥secureContext: TLS context object created with tls.createSecureContext(). If a secureContext is not provided, one will be created by passing the entire options object to tls.createSecureContext().

    • onread <Object> 如果缺少 socket 选项,则传入的数据将存储在单个 buffer 中,并在数据到达套接字时传递给提供的 callback,否则该选项将被忽略。详见 net.Socketonread 选项。

      ¥onread <Object> If the socket option is missing, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket, otherwise the option is ignored. See the onread option of net.Socket for details.

    • ...:如果缺少 secureContext 选项,则使用 tls.createSecureContext() 选项,否则将忽略它们。

      ¥...: tls.createSecureContext() options that are used if the secureContext option is missing, otherwise they are ignored.

    • ...:任何尚未列出的 socket.connect() 选项。

      ¥...: Any socket.connect() option not already listed.

  • callback <Function>

  • 返回:<tls.TLSSocket>

    ¥Returns: <tls.TLSSocket>

callback 函数,如果指定,则将被添加为 'secureConnect' 事件的监听器。

¥The callback function, if specified, will be added as a listener for the 'secureConnect' event.

tls.connect() 返回 tls.TLSSocket 对象。

¥tls.connect() returns a tls.TLSSocket object.

https API 不同,tls.connect() 默认不启用 SNI(服务器名称指示)扩展,这可能会导致部分服务器返回错误证书或完全拒绝连接。要启用 SNI,除了 host 之外,还要设置 servername 选项。

¥Unlike the https API, tls.connect() does not enable the SNI (Server Name Indication) extension by default, which may cause some servers to return an incorrect certificate or reject the connection altogether. To enable SNI, set the servername option in addition to host.

以下说明了来自 tls.createServer() 的回显服务器示例的客户端:

¥The following illustrates a client for the echo server example from tls.createServer():

// Assumes an echo server that is listening on port 8000.
const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  // Necessary only if the server requires client certificate authentication.
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses a self-signed certificate.
  ca: [ fs.readFileSync('server-cert.pem') ],

  // Necessary only if the server's cert isn't for "localhost".
  checkServerIdentity: () => { return null; },
};

const socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  console.log('server ends connection');
}); 

tls.connect(path[, options][, callback])#

tls.connect() 相同,除了 path 可以作为参数而不是选项提供。

¥Same as tls.connect() except that path can be provided as an argument instead of an option.

路径选项,如果指定,将优先于路径参数。

¥A path option, if specified, will take precedence over the path argument.

tls.connect(port[, host][, options][, callback])#

tls.connect() 相同,除了 porthost 可以作为参数而不是选项提供。

¥Same as tls.connect() except that port and host can be provided as arguments instead of options.

端口或主机选项,如果指定,将优先于任何端口或主机参数。

¥A port or host option, if specified, will take precedence over any port or host argument.

tls.createSecureContext([options])#

  • options <Object>

    • allowPartialTrustChain <boolean> 将信任 CA 证书列表中的中间(非自签名)证书视为受信任。

      ¥allowPartialTrustChain <boolean> Treat intermediate (non-self-signed) certificates in the trust CA certificate list as trusted.

    • ca <string> | <string[]> | <Buffer> | <Buffer[]> 可选择覆盖受信任的 CA 证书。默认是信任 Mozilla 策划的知名 CA。当使用此选项明确指定 CA 时,Mozilla 的 CA 将被完全替换。该值可以是字符串或 Buffer,或字符串的 Array 和/或 Buffer。任何字符串或 Buffer 都可以包含多个连接在一起的 PEM CA。对等方的证书必须可链接到服务器信任的 CA 才能对连接进行身份验证。当使用不可链接到知名 CA 的证书时,必须明确指定证书的 CA 为受信任的 CA,否则连接将无法通过身份验证。如果对等方使用的证书不匹配或链接到默认 CA 之一,则使用 ca 选项提供对等方证书可以匹配或链接到的 CA 证书。对于自签名证书,证书是自己的 CA,必须提供。对于 PEM 编码证书,支持的类型为 "TRUSTED CERTIFICATE"、"X509 CERTIFICATE" 和 "CERTIFICATE"。另见 tls.rootCertificates

      ¥ca <string> | <string[]> | <Buffer> | <Buffer[]> Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or Buffer, or an Array of strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the ca option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE". See also tls.rootCertificates.

    • cert <string> | <string[]> | <Buffer> | <Buffer[]> PEM 格式的证书链。每个私钥应提供证书链。每个证书链都应包含提供的私有 key 的 PEM 格式证书,然后是 PEM 格式的中间证书(如果有),按顺序排列,并且不包括根 CA(根 CA 必须是对等方预先知道的,参见 ca)。在提供多个证书链时,它们不必与 key 中的私钥顺序相同。如果不提供中间证书,则对端将无法验证证书,握手将失败。

      ¥cert <string> | <string[]> | <Buffer> | <Buffer[]> Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.

    • sigalgs <string> 支持的签名算法的冒号分隔列表。该列表可以包含摘要算法(SHA256MD5 等)、公钥算法(RSA-PSSECDSA 等)、两者的组合(例如 'RSA+SHA384')或 TLS v1.3 方案名称(例如 rsa_pss_pss_sha512)。有关详细信息,请参阅 OpenSSL 手册页

      ¥sigalgs <string> Colon-separated list of supported signature algorithms. The list can contain digest algorithms (SHA256, MD5 etc.), public key algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). See OpenSSL man pages for more info.

    • ciphers <string> 密码套件规范,替换默认值。有关详细信息,请参阅 修改默认的 TLS 密码套件。可以通过 tls.getCiphers() 获得允许的密码。密码名称必须大写,OpenSSL 才能接受它们。

      ¥ciphers <string> Cipher suite specification, replacing the default. For more information, see Modifying the default TLS cipher suite. Permitted ciphers can be obtained via tls.getCiphers(). Cipher names must be uppercased in order for OpenSSL to accept them.

    • clientCertEngine <string> 可以提供客户端证书的 OpenSSL 引擎的名称。已弃用。

      ¥clientCertEngine <string> Name of an OpenSSL engine which can provide the client certificate. Deprecated.

    • crl <string> | <string[]> | <Buffer> | <Buffer[]> PEM 格式的 CRL(证书吊销列表)。

      ¥crl <string> | <string[]> | <Buffer> | <Buffer[]> PEM formatted CRLs (Certificate Revocation Lists).

    • dhparam <string> | <Buffer> 'auto' 或自定义 Diffie-Hellman 参数,非 ECDHE 完全前向保密 所需。如果省略或无效,参数将被静默丢弃,DHE 密码将不可用。基于 ECDHE完全前向保密 仍将可用。

      ¥dhparam <string> | <Buffer> 'auto' or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. ECDHE-based perfect forward secrecy will still be available.

    • ecdhCurve <string> 描述命名曲线或以冒号分隔的曲线 NID 或名称列表的字符串,例如 P-521:P-384:P-256,用于 ECDH 密钥协议。设置为 auto 自动选择曲线。使用 crypto.getCurves() 获取可用曲线名称的列表。在最近的版本中,openssl ecparam -list_curves 还将显示每个可用椭圆曲线的名称和描述。默认值:tls.DEFAULT_ECDH_CURVE

      ¥ecdhCurve <string> A string describing a named curve or a colon separated list of curve NIDs or names, for example P-521:P-384:P-256, to use for ECDH key agreement. Set to auto to select the curve automatically. Use crypto.getCurves() to obtain a list of available curve names. On recent releases, openssl ecparam -list_curves will also display the name and description of each available elliptic curve. Default: tls.DEFAULT_ECDH_CURVE.

    • honorCipherOrder <boolean> 尝试使用服务器的密码套件首选项而不是客户端的。当 true 时,导致 SSL_OP_CIPHER_SERVER_PREFERENCEsecureOptions 中设置,请参阅 OpenSSL 选项 了解更多信息。

      ¥honorCipherOrder <boolean> Attempt to use the server's cipher suite preferences instead of the client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions, see OpenSSL Options for more information.

    • key <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PEM 格式的私钥。PEM 允许选择加密私钥。加密的密钥将用 options.passphrase 解密。使用不同算法的多个密钥可以作为未加密密钥字符串或缓冲区的数组提供,也可以作为 {pem: <string|buffer>[, passphrase: <string>]} 形式的对象数组提供。对象形式只能出现在数组中。object.passphrase 是可选的。如果提供了加密的密钥,则将使用 object.passphrase 解密,否则使用 options.passphrase 解密。

      ¥key <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.

    • privateKeyEngine <string> 从中获取私钥的 OpenSSL 引擎的名称。应与 privateKeyIdentifier 一起使用。已弃用。

      ¥privateKeyEngine <string> Name of an OpenSSL engine to get private key from. Should be used together with privateKeyIdentifier. Deprecated.

    • privateKeyIdentifier <string> 由 OpenSSL 引擎管理的私钥的标识符。应与 privateKeyEngine 一起使用。不应与 key 一起设置,因为这两个选项定义的私钥的方式不同。已弃用。

      ¥privateKeyIdentifier <string> Identifier of a private key managed by an OpenSSL engine. Should be used together with privateKeyEngine. Should not be set together with key, because both options define a private key in different ways. Deprecated.

    • maxVersion <string> 可选择设置允许的最大 TLS 版本。'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1' 之一。不能与 secureProtocol 选项一起指定;使用一个或另一个。默认值:tls.DEFAULT_MAX_VERSION

      ¥maxVersion <string> Optionally set the maximum TLS version to allow. One of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified along with the secureProtocol option; use one or the other. Default: tls.DEFAULT_MAX_VERSION.

    • minVersion <string> 可选择设置允许的最低 TLS 版本。'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1' 之一。不能与 secureProtocol 选项一起指定;使用一个或另一个。避免设置为低于 TLSv1.2,但可能需要互操作性。默认值:tls.DEFAULT_MIN_VERSION

      ¥minVersion <string> Optionally set the minimum TLS version to allow. One of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified along with the secureProtocol option; use one or the other. Avoid setting to less than TLSv1.2, but it may be required for interoperability. Default: tls.DEFAULT_MIN_VERSION.

    • passphrase <string> 用于单个私钥和/或 PFX 的共享密码。

      ¥passphrase <string> Shared passphrase used for a single private key and/or a PFX.

    • pfx <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PFX 或 PKCS12 编码的私钥和证书链。pfx 是单独提供 keycert 的替代方案。PFX 通常是加密的,如果是的话,会用 passphrase 来解密。多个 PFX 可以作为未加密的 PFX 缓冲区数组或 {buf: <string|buffer>[, passphrase: <string>]} 形式的对象数组提供。对象形式只能出现在数组中。object.passphrase 是可选的。如果提供加密的 PFX 将使用 object.passphrase 解密,否则将使用 options.passphrase 解密。

      ¥pfx <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PFX or PKCS12 encoded private key and certificate chain. pfx is an alternative to providing key and cert individually. PFX is usually encrypted, if it is, passphrase will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form {buf: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.

    • secureOptions <number> 可选地影响 OpenSSL 协议行为,这通常不是必需的。如果有的话应该小心使用!值是来自 OpenSSL 选项SSL_OP_* 选项的数字位掩码。

      ¥secureOptions <number> Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options.

    • secureProtocol <string> 选择要使用的 TLS 协议版本的旧机制,它不支持独立控制最低和最高版本,也不支持将协议限制为 TLSv1.3。请改用 minVersionmaxVersion。可能的值列为 SSL_METHODS,使用函数名称作为字符串。例如,使用 'TLSv1_1_method' 强制使用 TLS 版本 1.1,或使用 'TLS_method' 允许最高 TLSv1.3 的任何 TLS 协议版本。不建议使用低于 1.2 的 TLS 版本,但可能需要互操作性。默认值:无,参见 minVersion

      ¥secureProtocol <string> Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use minVersion and maxVersion instead. The possible values are listed as SSL_METHODS, use the function names as strings. For example, use 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. Default: none, see minVersion.

    • sessionIdContext <string> 服务器使用不透明标识符来确保应用之间不共享会话状态。客户端未使用。

      ¥sessionIdContext <string> Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.

    • ticketKeys<Buffer> 48 字节的加密强伪随机数据。有关详细信息,请参阅 会话恢复

      ¥ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information.

    • sessionTimeout <number> 服务器创建的 TLS 会话将无法恢复之前的秒数。有关详细信息,请参阅 会话恢复。默认值:300

      ¥sessionTimeout <number> The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default: 300.

tls.createServer()honorCipherOrder 选项的默认值设置为 true,创建安全上下文的其他 API 未设置。

¥tls.createServer() sets the default value of the honorCipherOrder option to true, other APIs that create secure contexts leave it unset.

tls.createServer() 使用从 process.argv 生成的 128 位截断 SHA1 哈希值作为 sessionIdContext 选项的默认值,其他创建安全上下文的 API 没有默认值。

¥tls.createServer() uses a 128 bit truncated SHA1 hash value generated from process.argv as the default value of the sessionIdContext option, other APIs that create secure contexts have no default value.

tls.createSecureContext() 方法创建了 SecureContext 对象。它可用作几个 tls API 的参数,例如 server.addContext(),但没有公共方法。tls.Server 构造函数和 tls.createServer() 方法不支持 secureContext 选项。

¥The tls.createSecureContext() method creates a SecureContext object. It is usable as an argument to several tls APIs, such as server.addContext(), but has no public methods. The tls.Server constructor and the tls.createServer() method do not support the secureContext option.

使用证书的密码需要密钥。keypfx 都可以提供。

¥A key is required for ciphers that use certificates. Either key or pfx can be used to provide it.

如果没有给出 ca 选项,那么 Node.js 将默认使用 Mozilla 公开信任的 CA 列表

¥If the ca option is not given, then Node.js will default to using Mozilla's publicly trusted list of CAs.

不鼓励自定义 DHE 参数以支持新的 dhparam: 'auto' 选项。当设置为 'auto' 时,将自动选择具有足够强度的知名 DHE 参数。否则,如有必要,openssl dhparam 可用于创建自定义参数。密钥长度必须大于等于 1024 位,否则会报错。虽然 1024 位是允许的,但为了更强的安全性,请使用 2048 位或更大的位。

¥Custom DHE parameters are discouraged in favor of the new dhparam: 'auto' option. When set to 'auto', well-known DHE parameters of sufficient strength will be selected automatically. Otherwise, if necessary, openssl dhparam can be used to create custom parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security.

tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])#

稳定性: 0 - 已弃用:改用 tls.TLSSocket

¥Stability: 0 - Deprecated: Use tls.TLSSocket instead.

  • context <Object> tls.createSecureContext() 返回的安全上下文对象

    ¥context <Object> A secure context object as returned by tls.createSecureContext()

  • isServer <boolean> true 指定此 TLS 连接应作为服务器打开。

    ¥isServer <boolean> true to specify that this TLS connection should be opened as a server.

  • requestCert <boolean> true 指定服务器是否应向连接客户端请求证书。仅在 isServertrue 时适用。

    ¥requestCert <boolean> true to specify whether a server should request a certificate from a connecting client. Only applies when isServer is true.

  • rejectUnauthorized <boolean> 如果不是 false,则服务器会自动拒绝证书无效的客户端。仅在 isServertrue 时适用。

    ¥rejectUnauthorized <boolean> If not false a server automatically reject clients with invalid certificates. Only applies when isServer is true.

  • options

使用两个流创建新的安全对对象,其中一个读取和写入加密数据,另一个读取和写入明文数据。通常,加密流通过管道传输到/从传入的加密数据流,明文用作初始加密流的替代。

¥Creates a new secure pair object with two streams, one of which reads and writes the encrypted data and the other of which reads and writes the cleartext data. Generally, the encrypted stream is piped to/from an incoming encrypted data stream and the cleartext one is used as a replacement for the initial encrypted stream.

tls.createSecurePair() 返回具有 cleartextencrypted 流属性的 tls.SecurePair 对象。

¥tls.createSecurePair() returns a tls.SecurePair object with cleartext and encrypted stream properties.

使用 cleartexttls.TLSSocket 具有相同的 API。

¥Using cleartext has the same API as tls.TLSSocket.

现在不推荐使用 tls.createSecurePair() 方法而支持 tls.TLSSocket()。例如代码:

¥The tls.createSecurePair() method is now deprecated in favor of tls.TLSSocket(). For example, the code:

pair = tls.createSecurePair(/* ... */);
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted); 

可以替换为:

¥can be replaced by:

secureSocket = tls.TLSSocket(socket, options); 

其中 secureSocketpair.cleartext 具有相同的 API。

¥where secureSocket has the same API as pair.cleartext.

tls.createServer([options][, secureConnectionListener])#

  • options <Object>

    • ALPNProtocols<string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 包含支持的 ALPN 协议的字符串数组 BufferTypedArrayDataView,或单个 BufferTypedArrayDataViewBuffer 应采用 [len][name][len][name]... 格式,例如 0x05hello0x05world,其中第一个字节是下一个协议名称的长度。传入数组通常要简单得多,例如 ['hello', 'world']。(协议应按优先级排序。)

      ¥ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings, Buffers, TypedArrays, or DataViews, or a single Buffer, TypedArray, or DataView containing the supported ALPN protocols. Buffers should have the format [len][name][len][name]... e.g. 0x05hello0x05world, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['hello', 'world']. (Protocols should be ordered by their priority.)

    • ALPNCallback<Function> 如果设置,当客户端使用 ALPN 扩展打开连接时将调用此函数。一个参数将被传递给回调:包含 servernameprotocols 字段的对象,分别包含 SNI 扩展中的服务器名称(如果有)和 ALPN 协议名称字符串数组。回调必须返回 protocols 中列出的字符串之一(该字符串将作为选定的 ALPN 协议返回给客户端)或 undefined(以致命警报拒绝连接)。如果返回的字符串与客户端的 ALPN 协议之一不匹配,则会抛出错误。该选项不能与 ALPNProtocols 选项一起使用,设置这两个选项将引发错误。

      ¥ALPNCallback: <Function> If set, this will be called when a client opens a connection using the ALPN extension. One argument will be passed to the callback: an object containing servername and protocols fields, respectively containing the server name from the SNI extension (if any) and an array of ALPN protocol name strings. The callback must return either one of the strings listed in protocols, which will be returned to the client as the selected ALPN protocol, or undefined, to reject the connection with a fatal alert. If a string is returned that does not match one of the client's ALPN protocols, an error will be thrown. This option cannot be used with the ALPNProtocols option, and setting both options will throw an error.

    • clientCertEngine <string> 可以提供客户端证书的 OpenSSL 引擎的名称。已弃用。

      ¥clientCertEngine <string> Name of an OpenSSL engine which can provide the client certificate. Deprecated.

    • enableTrace <boolean> 如果为 true, 则 tls.TLSSocket.enableTrace() 将在新连接上调用。建立安全连接后可以启用跟踪,但必须使用此选项来跟踪安全连接设置。默认值:false

      ¥enableTrace <boolean> If true, tls.TLSSocket.enableTrace() will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. Default: false.

    • handshakeTimeout <number> 如果 SSL/TLS 握手未在指定的毫秒数内完成,则中止连接。每当握手超时时,tls.Server 对象上就会触发 'tlsClientError'。默认值:120000(120 秒)。

      ¥handshakeTimeout <number> Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A 'tlsClientError' is emitted on the tls.Server object whenever a handshake times out. Default: 120000 (120 seconds).

    • rejectUnauthorized <boolean> 如果不是 false,则服务器将拒绝任何未经提供的 CA 列表授权的连接。此选项仅在 requestCerttrue 时有效。默认值:true

      ¥rejectUnauthorized <boolean> If not false the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true. Default: true.

    • requestCert <boolean> 如果为 true,则服务器将从连接的客户端请求证书并尝试验证该证书。默认值:false

      ¥requestCert <boolean> If true the server will request a certificate from clients that connect and attempt to verify that certificate. Default: false.

    • sessionTimeout <number> 服务器创建的 TLS 会话将无法恢复之前的秒数。有关详细信息,请参阅 会话恢复。默认值:300

      ¥sessionTimeout <number> The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default: 300.

    • SNICallback(servername, callback) <Function> 如果客户端支持 SNI TLS 扩展,将调用的函数。调用时将传递两个参数:servernamecallbackcallback 是一个错误优先回调,它有两个可选参数:errorctxctxSecureContext 实例(如果提供)。tls.createSecureContext() 可用于获得正确的 SecureContext。如果使用非真的 ctx 参数调用 callback,则将使用服务器的默认安全上下文。如果未提供 SNICallback,则将使用具有高级 API 的默认回调(见下文)。

      ¥SNICallback(servername, callback) <Function> A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: servername and callback. callback is an error-first callback that takes two optional arguments: error and ctx. ctx, if provided, is a SecureContext instance. tls.createSecureContext() can be used to get a proper SecureContext. If callback is called with a falsy ctx argument, the default secure context of the server will be used. If SNICallback wasn't provided the default callback with high-level API will be used (see below).

    • ticketKeys<Buffer> 48 字节的加密强伪随机数据。有关详细信息,请参阅 会话恢复

      ¥ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information.

    • pskCallback <Function> 对于 TLS-PSK 协商,请参阅 预共享密钥

      ¥pskCallback <Function> For TLS-PSK negotiation, see Pre-shared keys.

    • pskIdentityHint <string> 发送给客户端的可选提示,以帮助在 TLS-PSK 协商期间选择身份。在 TLS 1.3 中将被忽略。如果设置 pskIdentityHint 失败,将触发 'tlsClientError''ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' 代码。

      ¥pskIdentityHint <string> optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint 'tlsClientError' will be emitted with 'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' code.

    • ...:可以提供任何 tls.createSecureContext() 选项。对于服务器,通常需要标识选项(pfxkey/certpskCallback)。

      ¥...: Any tls.createSecureContext() option can be provided. For servers, the identity options (pfx, key/cert, or pskCallback) are usually required.

    • ...:可以提供任何 net.createServer() 选项。

      ¥...: Any net.createServer() option can be provided.

  • secureConnectionListener <Function>

  • 返回:<tls.Server>

    ¥Returns: <tls.Server>

创建新的 tls.ServersecureConnectionListener,如果提供,将自动设置为 'secureConnection' 事件的监听器。

¥Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the 'secureConnection' event.

ticketKeys 选项在 node:cluster 模块工作器之间自动共享。

¥The ticketKeys options is automatically shared between node:cluster module workers.

以下说明了一个简单的回显服务器:

¥The following illustrates a simple echo server:

const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using client certificate authentication.
  requestCert: true,

  // This is necessary only if the client uses a self-signed certificate.
  ca: [ fs.readFileSync('client-cert.pem') ],
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
}); 

可以通过使用 tls.connect() 的示例客户端连接到服务器来测试服务器。

¥The server can be tested by connecting to it using the example client from tls.connect().

tls.getCiphers()#

返回包含支持的 TLS 密码名称的数组。由于历史原因,名称为小写,但必须大写才能在 tls.createSecureContext()ciphers 选项中使用。

¥Returns an array with the names of the supported TLS ciphers. The names are lower-case for historical reasons, but must be uppercased to be used in the ciphers option of tls.createSecureContext().

并非所有支持的密码都默认启用。参见 修改默认的 TLS 密码套件

¥Not all supported ciphers are enabled by default. See Modifying the default TLS cipher suite.

'tls_' 开头的密码名称适用于 TLSv1.3,所有其他密码均适用于 TLSv1.2 及以下。

¥Cipher names that start with 'tls_' are for TLSv1.3, all the others are for TLSv1.2 and below.

console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] 

tls.rootCertificates#

不可变的字符串数组,代表当前 Node.js 版本提供的打包 Mozilla CA 存储中的根证书(PEM 格式)。

¥An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.

Node.js 提供的打包 CA 存储是 Mozilla CA 存储的快照,在发布时已修复。它在所有支持的平台上都是相同的。

¥The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.

tls.DEFAULT_ECDH_CURVE#

tls 服务器中用于 ECDH 密钥协议的默认曲线名称。默认值为 'auto'。请参阅 tls.createSecureContext() 了解更多信息。

¥The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See tls.createSecureContext() for further information.

tls.DEFAULT_MAX_VERSION#

  • <string> tls.createSecureContext()maxVersion 选项的默认值。可以为其分配任何受支持的 TLS 协议版本:'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'。默认值:'TLSv1.3',除非使用 CLI 选项进行更改。使用 --tls-max-v1.2 将默认设置为 'TLSv1.2'。使用 --tls-max-v1.3 将默认设置为 'TLSv1.3'。如果提供多个选项,则使用最高的最大值。

    ¥<string> The default value of the maxVersion option of tls.createSecureContext(). It can be assigned any of the supported TLS protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the highest maximum is used.

tls.DEFAULT_MIN_VERSION#

  • <string> tls.createSecureContext()minVersion 选项的默认值。可以为其分配任何受支持的 TLS 协议版本:'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'。默认值:'TLSv1.2',除非使用 CLI 选项进行更改。使用 --tls-min-v1.0 将默认设置为 'TLSv1'。使用 --tls-min-v1.1 将默认设置为 'TLSv1.1'。使用 --tls-min-v1.3 将默认设置为 'TLSv1.3'。如果提供多个选项,则使用最低的最小值。

    ¥<string> The default value of the minVersion option of tls.createSecureContext(). It can be assigned any of the supported TLS protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless changed using CLI options. Using --tls-min-v1.0 sets the default to 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.

tls.DEFAULT_CIPHERS#

  • <string> tls.createSecureContext()ciphers 选项的默认值。可以为其分配任何受支持的 OpenSSL 密码。默认为 crypto.constants.defaultCoreCipherList 的内容,除非使用 --tls-default-ciphers 使用 CLI 选项进行更改。

    ¥<string> The default value of the ciphers option of tls.createSecureContext(). It can be assigned any of the supported OpenSSL ciphers. Defaults to the content of crypto.constants.defaultCoreCipherList, unless changed using CLI options using --tls-default-ciphers.

Node.js 中文网 - 粤ICP备13048890号