原创文章,转载请注明出处:服务器非业余研究http://blog.csdn.net/erlib 作者Sunface
最近准备写一个SSL服务器,结果发现网上相关的资料很少,因为特地在此给大家分享一下SSL的基本使用方法.
SSL在使用上跟Tcp很像,但是也由区别。首先需要一个SSL证书,可以在参考这篇文章创建。
下面的代码实现了服务端和客户端,对于有经验erlang同学,应该很容易理解了,就不赘述了。
服务器端
- -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证书
时间: 2024-11-09 04:50:41