原创文章,转载请注明出处:server非业余研究http://blog.csdn.net/erlib 作者Sunface


   近期准备写一个SSLserver,结果发现网上相关的资料非常少,由于特地在此给大家分享一下SSL的基本用法.

SSL在使用上跟Tcp非常像,可是也由差别。

首先须要一个SSL证书。能够在參考​​这篇文章​​创建。

以下的代码实现了服务端和客户端。对于有经验erlang同学,应该非常easy理解了,就不赘述了。


server端

1. 

2.
-module(s).


3.
-export([start/0, client/1, accept/1]).


4.



5.
start() ->


6.
ssl:start(),


7.
server(4000).


8.



9.
server(Port) ->


10.
{ok, LSocket} = ssl:listen(Port, [{certfile,"certificate.pem"}, {keyfile, "key.pem"}, {reuseaddr, true}, {active, false}]),


11.
spawn(fun() -> accept(LSocket) end).


12.



13.
accept(LSocket) ->


14.
{ok, Socket} = ssl:transport_accept(LSocket),


15.
Pid = spawn(fun() ->


16.
io:format("Connection accepted ~p~n", [Socket]),


17.
loop(Socket)


18.
end),


19.
ssl:controlling_process(Socket, Pid),


20.
accept(LSocket).


21.



22.
loop(Socket) ->


23.
ssl:setopts(Socket, [{active, once}]),


24.
receive


25.
{ssl,Sock, Data} ->


26.
io:format("Got packet: ~p~n", [Data]),


27.
ssl:send(Sock, Data),


28.
loop(Socket);


29.
{ssl_closed, Sock} ->


30.
io:format("Closing socket: ~p~n", [Sock]);


31.
Error ->


32.
io:format("Error on socket: ~p~n", [Error])


33.
end.

34.


客户端:

1. 

2.
client(N) ->


3.
{ok, Socket} = ssl:connect("localhost", 4000, []),


4.
io:format("Client opened socket: ~p~n",[Socket]),


5.
ok = ssl:send(Socket, N),


6.
Value = receive


7.
{ssl,{sslsocket,new_ssl,_}, Data} ->


8.
io:format("Client received: ~p~n",[Data])


9.
after 2000 ->


10.
0


11.
end,


12.
ssl:close(Socket),


13.
Value.

14.



1. 

2.
$ erl


3.
Eshell V5.8.5 (abort with ^G)


4.
1> c(s).


5.
{ok,s}


6.
2> s:start().


7.
<0.52.0>


8.
Connection accepted {sslsocket,new_ssl,<0.54.0>}


9.
Got packet: "Hello"


10.
Closing socket: {sslsocket,new_ssl,<0.54.0>}

11.


别忘了在客户端进程启动ssl服务

1. 

2.
$ erl


3.
Eshell V5.8.5 (abort with ^G)


4.
1> ssl:start().


5.
ok


6.
2> s:client("Hello").


7.
Client opened socket: {sslsocket,new_ssl,<0.49.0>}


8.
Client received: "Hello"


9. ok
10.



由于是SSL。所以须要安全验证:

1.option中得 verify设置,验证peer(对端)的合法性

  • 0 - 不验证
  • 1 -  验证 
  • 2 - 验证。同一时候peer假设没有证书,验证失败


2.depth验证,此选项指定了同意验证几个证书,同意值0-N


  • 0 - 仅仅验证peer证书
  • 1 -  验证CA证书
  • 2 - 验证多本CA证书