99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

使用 SSL/TLS 加密 Netty 程序

2018-08-08 10:41 更新

現(xiàn)在數(shù)據(jù)隱私問題受到越來越多人的關(guān)注,開發(fā)人員在進(jìn)行開發(fā)的時候必須把這個問題考慮好。最基礎(chǔ)的就是需要熟悉加密協(xié)議 SSL 和 TLS 等更上一層的其他協(xié)議來實現(xiàn)數(shù)據(jù)安全。作為一個 HTTPS 網(wǎng)站的用戶,你是安全的。當(dāng)然,這些協(xié)議是廣泛不基于 http 的應(yīng)用程序,例如安全SMTP(SMTPS)郵件服務(wù),甚至于關(guān)系數(shù)據(jù)庫系統(tǒng)。 

為了支持 SSL/TLS,Java 提供了 javax.net.ssl API 的類SslContext 和 SslEngine 使它相對簡單的實現(xiàn)解密和加密。Netty 的利用該 API 命名 SslHandler 的 ChannelHandler 實現(xiàn), 有一個內(nèi)部 SslEngine 做實際的工作。

圖8.1顯示了一個使用 SslHandler 數(shù)據(jù)流圖。

Figure%208

  1. 加密的入站數(shù)據(jù)被 SslHandler 攔截,并被解密
  2. 前面加密的數(shù)據(jù)被 SslHandler 解密
  3. 平常數(shù)據(jù)傳過 SslHandler
  4. SslHandler 加密數(shù)據(jù)并它傳遞出站

Figure 8.1 Data flow through SslHandler for decryption and encryption

如清單8.1所示一個 SslHandler 使用 ChannelInitializer 添加到 ChannelPipeline。(回想一下,當(dāng) Channel 注冊時 ChannelInitializer 用于設(shè)置 ChannelPipeline 。)

Listing 8.1 Add SSL/TLS support

public class SslChannelInitializer extends ChannelInitializer<Channel> {

    private final SslContext context;
    private final boolean startTls;
    public SslChannelInitializer(SslContext context,
    boolean client, boolean startTls) {   //1
        this.context = context;
        this.startTls = startTls;
    }
    @Override
    protected void initChannel(Channel ch) throws Exception {
        SSLEngine engine = context.newEngine(ch.alloc());  //2
        engine.setUseClientMode(client); //3
        ch.pipeline().addFirst("ssl", new SslHandler(engine, startTls));  //4
    }
}
  1. 使用構(gòu)造函數(shù)來傳遞 SSLContext 用于使用(startTls 是否啟用)
  2. 從 SslContext 獲得一個新的 SslEngine 。給每個 SslHandler 實例使用一個新的 SslEngine
  3. 設(shè)置 SslEngine 是 client 或者是 server 模式
  4. 添加 SslHandler 到 pipeline 作為第一個處理器

在大多數(shù)情況下,SslHandler 將成為 ChannelPipeline 中的第一個 ChannelHandler 。這將確保所有其他 ChannelHandler 應(yīng)用他們的邏輯到數(shù)據(jù)后加密后才發(fā)生,從而確保他們的變化是安全的。

SslHandler 有很多有用的方法,如表8.1所示。例如,在握手階段兩端相互驗證,商定一個加密方法。您可以配置 SslHandler 修改其行為或提供 在SSL/TLS 握手完成后發(fā)送通知,這樣所有數(shù)據(jù)都將被加密。 SSL/TLS 握手將自動執(zhí)行。

Table 8.1 SslHandler methods

名稱描述
setHandshakeTimeout(...) setHandshakeTimeoutMillis(...) getHandshakeTimeoutMillis()Set and get the timeout, after which the handshake ChannelFuture is notified of failure.
setCloseNotifyTimeout(...) setCloseNotifyTimeoutMillis(...) getCloseNotifyTimeoutMillis()Set and get the timeout after which the close notify will time out and the connection will close. This also results in having the close notify ChannelFuture fail.
handshakeFuture()Returns a ChannelFuture that will be notified once the handshake is complete. If the handshake was done before it will return a ChannelFuture that contains the result of the previous handshake.
close(...)Send the close_notify to request close and destroy the underlying SslEngine.


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號