erlang的token值加解密

     對於加解密,需客戶端和服務器制定好對應的規則(如:加密算法(aes,des等)、加密模式(cbc,cfb)),去加密,再按逆序列解密。這裏的key是根據數字、大小寫字母、符合組合的,每次請求獲取一個動態key,暫且叫作」一次一密鑰「;前端

而也能夠設計爲:先後端一開始定義好一個固定key,這樣好處是:就不需獲取隨機key,也不須要在最後把加密內容和Key穿插起來發送,只需給需加密的內容加密便可。c++

但這樣的壞處是:若是拿到固定的key,就能夠模擬前端報文連續給server端發消息,key的級別不強;而每次隨機獲取key相對就行了不少。算法

   下面附erlang作客戶端加密部分代碼及服務端解密部分代碼:後端

 1 -module(cc).
 2 
 3 -compile(export_all).
 4 
 5 -define(TOKEN_IVEC, <<"Egl63xPQYEcIY0RJ">>).
 6  
 7 %%client加密部分
 8 aes_encode() ->
 9    Time = list_to_binary(integer_to_list(unixtime1()) ++"000" ),
10    io:format("Time...client...~p~n",[Time]),
11    Key  = list_to_binary(random()),
12    io:format("Key...client...~p~n",[Key]),
13    AES = crypto:aes_cbc_128_encrypt(Key, ?TOKEN_IVEC, Time),
14    Text = base64:encode(AES),
15    Text1 = binary_to_list(Text),
16    End =  foldl(lists:sublist(Text1,1,16),binary_to_list(Key)) ++ lists:sublist(Text1,17,8),
17    End.
18 
19 %隨機生成16位Key值
20  random() ->
21   Str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",
22   %%一次隨機取多個,再分別取出對應值
23   N = [random:uniform(length(Str)) || _Elem <- lists:seq(1,16)],
24   RandomKey = [lists:nth(X,Str) || X<- N ],
25   RandomKey.     
26 
27 unixtime1() ->
28     {MegaSecs, Secs, _MicroSecs} = erlang:now(),
29     MegaSecs * 1000000000 + Secs * 100000 .
30 
31 foldl(A, B) ->
32     foldl(A, B, []).
33 foldl([H|T], [H1|T1], Acc) ->
34     foldl(T, T1, Acc++[H|[H1]]);
35 foldl([], [], Acc) ->
36     Acc.
37 
38 
39 
40 
41 %%server解密部分
42 verify_token( Token ) ->
43     case Token of
44         "" ->
45             {error, "token error"};
46         TokenStr ->
47             {CryptoStr, Key} = verify_token_scan(TokenStr, <<>>, <<>>, 16),
48   io:format("Key...server...~p~n",[Key]),
49             Cipher = base64:decode(CryptoStr),
50             TimestampStr = binary_to_list(crypto:aes_cbc_128_decrypt(Key, ?TOKEN_IVEC, Cipher)),
51             Timestamp = list_to_integer(lists:sublist(TimestampStr, 13)),
52 
53 io:format("Timestamp ...server...~p~n",[Timestamp]),
54             Now = now_time(),
55             if
56                 Timestamp > (Now - 691200) * 1000 ->
57                     ok;
58                 true ->  
59                     {error, "1token error"}
60             end
61     end.
62     
63 now_time() ->
64      {X, Y, _} = now(),
65      X * 1000000 + Y.    
66     
67 verify_token_scan(TokenStr, CryptoStr, Key, 0) ->
68     {iolist_to_binary([CryptoStr, TokenStr]), Key};
69 verify_token_scan([C, K|TokenStr], CryptoStr, Key, KeyLength) ->            
70     verify_token_scan(TokenStr, <<CryptoStr/binary, C>>, <<Key/binary, K>>, KeyLength - 1);
71 verify_token_scan([], CryptoStr, Key, _KeyLength) -> 
72     {CryptoStr, Key}.
View Code

 

運行結果以下:服務器

 

涉及了隨機數的取法,加解密及base64轉碼以及反序列化的解密等東西.dom

相關文章
相關標籤/搜索