原創文章,轉載請註明出處:server非業餘研究http://blog.csdn.net/erlib 做者Sunfaceshell
近期準備寫一個SSLserver,結果發現網上相關的資料很是少,因爲特意在此給你們分享一下SSL的基本用法.安全
SSL在使用上跟Tcp很是像,但是也由差異。socket
首先需要一個SSL證書。可以在參考這篇文章建立。ide
如下的代碼實現了服務端和客戶端。對於有經驗erlang同窗,應該很是easy理解了,就不贅述了。oop
server端spa
- -module(s).
- -export([start/0, client/1, accept/1]).
- start() ->
- ssl:start(),
- server(4000).
- server(Port) ->
- {ok, LSocket} = ssl:listen(Port, [{certfile,"certificate.pem"}, {keyfile, "key.pem"}, {reuseaddr, true}, {active, false}]),
- spawn(fun() -> accept(LSocket) end).
-
- accept(LSocket) ->
- {ok, Socket} = ssl:transport_accept(LSocket),
- Pid = spawn(fun() ->
- io:format("Connection accepted ~p~n", [Socket]),
- loop(Socket)
- end),
- ssl:controlling_process(Socket, Pid),
- accept(LSocket).
- loop(Socket) ->
- ssl:setopts(Socket, [{active, once}]),
- receive
- {ssl,Sock, Data} ->
- io:format("Got packet: ~p~n", [Data]),
- ssl:send(Sock, Data),
- loop(Socket);
- {ssl_closed, Sock} ->
- io:format("Closing socket: ~p~n", [Sock]);
- Error ->
- io:format("Error on socket: ~p~n", [Error])
- end.
客戶端:.net
- client(N) ->
- {ok, Socket} = ssl:connect("localhost", 4000, []),
- io:format("Client opened socket: ~p~n",[Socket]),
- ok = ssl:send(Socket, N),
- Value = receive
- {ssl,{sslsocket,new_ssl,_}, Data} ->
- io:format("Client received: ~p~n",[Data])
- after 2000 ->
- 0
- end,
- ssl:close(Socket),
- Value.
- $ erl
- Eshell V5.8.5 (abort with ^G)
- 1> c(s).
- {ok,s}
- 2> s:start().
- <0.52.0>
- Connection accepted {sslsocket,new_ssl,<0.54.0>}
- Got packet: "Hello"
- Closing socket: {sslsocket,new_ssl,<0.54.0>}
別忘了在客戶端進程啓動ssl服務orm
- $ erl
- Eshell V5.8.5 (abort with ^G)
- 1> ssl:start().
- ok
- 2> s:client("Hello").
- Client opened socket: {sslsocket,new_ssl,<0.49.0>}
- Client received: "Hello"
- ok
因爲是SSL。因此需要安全驗證:server
1.option中得 verify設置,驗證peer(對端)的合法性blog
- 0 - 不驗證
- 1 - 驗證
- 2 - 驗證。同一時候peer假設沒有證書,驗證失敗
2.depth驗證,此選項指定了贊成驗證幾個證書,贊成值0-N
- 0 - 僅僅驗證peer證書
- 1 - 驗證CA證書
- 2 - 驗證多本CA證書