openssl genrsa -des3 -out privkey.pem 2048
生成一個長2048 bit的私鑰,并用密碼以DES算法加密該私鑰,最后輸出為名為privkey.pem的文件。
如果加密了該私鑰,則每次使用的時候都需要提供密碼,如果不需要密碼保謢,去掉-des3參數就可以了~~
openssl req -new -x509 -key privkey.pem -out cert.pem -days 1020
生成一個自簽的測試用證書,輸出為文件cert.pem,有效期為1020天。
然后用Erlang的SSL模塊實現一個ssl socket server和client:
-module(test).
-export([start/0, connect/0]).
%啟動SSL服務
start() ->
application:start(ssl),
ssl:seed("seed-every-time"),
{ok, spawn(fun() -> start_server() end)}.
%運行SSL SOCKET SERVER
start_server() ->
%創建socket server
{ok, ListenSocket} = ssl:listen(51020, [
binary, {active, true},
{keyfile, "privkey.pem"},
{certfile, "cert.pem"}]),
io:format("SSL socket server is ready\n", []),
%接受客戶端連接
{ok, Sock} = ssl:transport_accept(ListenSocket),
ok = ssl:ssl_accept(Sock),
io:format("New ssl client is connected\n", []),
loop_client(Sock).
%處理來自客戶端的信息
loop_client(Sock) ->
receive
{ssl, Sock, Data} ->
io:format("Receive : ~p\n", [Data]),
ssl:send(Sock, Data),
loop_client(Sock);
{ssl_closed, Sock} -> io:format("Client ~p is discionnected\n", [Sock]);
{ssl_errlr, Sock, Reason} -> io:format("ERROR : ~p\n", [Reason])
end.
%客戶端進行連接
connect() ->
{ok, Sock} = ssl:connect("localhost", 51020, [bianry]),
io:format("connected\n", []),
ssl:send(Sock, "this is just a test"),
receive
Any ->
io:format("client receive : ~p\n", [Any])
end,
ssl:close(Sock),
io:format("client closed\n", []).
測試一下能否正常運行:
1> c(test).
{ok,test}
2> test:start().
{ok,<0.46.0>}
SSL server socket is ready
3> test:connect().
New ssl client connected
connected
Receive : <<"this is just a test">>
client receive : {ssl,{sslsocket,6,<0.50.0>},<<"this is just a test">>}
client closed
ok
Client {sslsocket,7,<0.49.0>} is disconnected
哈哈,一切正常~~
发现了点问题,这样的SSL SOCKET只能接受ERLANG的SOCKET客户端,而用AS实现的TLSSOCKET却无法连接-_-