[Erlang]怎樣在Erlang中使用SSL

原創文章,轉載請註明出處:server非業餘研究http://blog.csdn.net/erlib 做者Sunfaceshell


   近期準備寫一個SSLserver,結果發現網上相關的資料很是少,因爲特意在此給你們分享一下SSL的基本用法.安全

SSL在使用上跟Tcp很是像,但是也由差異。socket

首先需要一個SSL證書。可以在參考這篇文章建立。ide

如下的代碼實現了服務端和客戶端。對於有經驗erlang同窗,應該很是easy理解了,就不贅述了。oop


server端spa

  
  
  
  
  1. -module(s).
  2. -export([start/0, client/1, accept/1]).

  3. start() ->
  4.    ssl:start(),
  5.    server(4000).

  6. server(Port) ->
  7.     {ok, LSocket} = ssl:listen(Port, [{certfile,"certificate.pem"}, {keyfile, "key.pem"}, {reuseaddr, true}, {active, false}]),
  8.     spawn(fun() -> accept(LSocket) end).
  9.    
  10. accept(LSocket) ->
  11.    {ok, Socket} = ssl:transport_accept(LSocket),
  12.    Pid = spawn(fun() ->
  13.         io:format("Connection accepted ~p~n", [Socket]),
  14.         loop(Socket)
  15.    end),
  16.    ssl:controlling_process(Socket, Pid),
  17.    accept(LSocket).

  18. loop(Socket) ->
  19.    ssl:setopts(Socket, [{active, once}]),
  20.    receive
  21.    {ssl,Sock, Data} ->
  22.         io:format("Got packet: ~p~n", [Data]),
  23.         ssl:send(Sock, Data),
  24.         loop(Socket);
  25.    {ssl_closed, Sock} ->
  26.         io:format("Closing socket: ~p~n", [Sock]);
  27.    Error ->
  28.         io:format("Error on socket: ~p~n", [Error])
  29.    end.

客戶端:.net

  
  
  
  
  1. client(N) ->
  2.     {ok, Socket} = ssl:connect("localhost", 4000,  []),
  3.     io:format("Client opened socket: ~p~n",[Socket]),
  4.     ok = ssl:send(Socket, N),
  5.     Value = receive
  6.             {ssl,{sslsocket,new_ssl,_}, Data} ->
  7.                 io:format("Client received: ~p~n",[Data])
  8.             after 2000 ->
  9.                 0
  10.             end,
  11.     ssl:close(Socket),
  12.     Value.


  
  
  
  
  1. $ erl
  2. Eshell V5.8.5  (abort with ^G)
  3. 1> c(s).
  4. {ok,s}
  5. 2> s:start().
  6. <0.52.0>
  7. Connection accepted {sslsocket,new_ssl,<0.54.0>}
  8. Got packet: "Hello"
  9. Closing socket: {sslsocket,new_ssl,<0.54.0>}

別忘了在客戶端進程啓動ssl服務orm

  
  
  
  
  1. $ erl
  2. Eshell V5.8.5  (abort with ^G)
  3. 1> ssl:start().
  4. ok
  5. 2> s:client("Hello").
  6. Client opened socket: {sslsocket,new_ssl,<0.49.0>}
  7. Client received: "Hello"
  8. ok


因爲是SSL。因此需要安全驗證:server

1.option中得 verify設置,驗證peer(對端)的合法性blog

  • 0 - 不驗證
  • 1 -  驗證 
  • 2 - 驗證。同一時候peer假設沒有證書,驗證失敗
2.depth驗證,此選項指定了贊成驗證幾個證書,贊成值0-N
  • 0 - 僅僅驗證peer證書
  • 1 -  驗證CA證書
  • 2 - 驗證多本CA證書
相關文章
相關標籤/搜索