原创文章,转载请注明出处:server非业余研究http://blog.csdn.net/erlib 作者Sunface
近期准备写一个SSLserver,结果发现网上相关的资料非常少,由于特地在此给大家分享一下SSL的基本用法.
SSL在使用上跟Tcp非常像,可是也由差别。
首先须要一个SSL证书。能够在參考这篇文章创建。
以下的代码实现了服务端和客户端。对于有经验erlang同学,应该非常easy理解了,就不赘述了。
server端
- -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.
客户端:
- 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服务
- $ 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。所以须要安全验证:
1.option中得 verify设置,验证peer(对端)的合法性
- 0 - 不验证
- 1 - 验证
- 2 - 验证。同一时候peer假设没有证书,验证失败
2.depth验证,此选项指定了同意验证几个证书,同意值0-N
- 0 - 仅仅验证peer证书
- 1 - 验证CA证书
- 2 - 验证多本CA证书