erlang des算法

-module(test_des).
-export([test/0]).

hexstr2bin(S) ->
    list_to_binary(hexstr2list(S)).

hexstr2list([X,Y|T]) ->
    [mkint(X)*16 + mkint(Y) | hexstr2list(T)];
hexstr2list([]) ->
    [].
mkint(C) when $0 =< C, C =< $9 ->
    C - $0;
mkint(C) when $A =< C, C =< $F ->
    C - $A + 10;
mkint(C) when $a =< C, C =< $f ->
    C - $a + 10.
    
bin_to_hexstr(Bin) ->
   lists:flatten([io_lib:format("~2.16.0B", [X]) ||
                  X <- binary_to_list(Bin)]).
 
hexstr_to_bin(S) ->
   hexstr_to_bin(S, []).
hexstr_to_bin([], Acc) ->
   list_to_binary(lists:reverse(Acc));
hexstr_to_bin([X,Y|T], Acc) ->
   {ok, [V], []} = io_lib:fread("~16u", [X,Y]),
   hexstr_to_bin(T, [V | Acc]).

test() ->

    io:format("[line:~w]test input string~w~n", [?LINE, "1234567890abcdef"]),
    CipherText1 = crypto:block_encrypt(des3_cbc,
     [hexstr2bin("0123456789abcdef"), 
      hexstr2bin("fedcba9876543210"),
      hexstr2bin("0f2d4b6987a5c3e1")],
     hexstr2bin("1234567890abcdef"),
     "1234567890abcdef"),
    io:format("[line:~w]~w~n", [?LINE, CipherText1]),

    io:format("[line:~w]test input hex~w~n", [?LINE, hexstr2bin("1234567890abcdef")]),
    CipherText = crypto:block_encrypt(des3_cbc,
     [hexstr2bin("0123456789abcdef"), 
      hexstr2bin("fedcba9876543210"),
      hexstr2bin("0f2d4b6987a5c3e1")],
     hexstr2bin("1234567890abcdef"),
     hexstr2bin("1234567890abcdef")),
    io:format("[line:~w]~w~n", [?LINE, CipherText]),
    PlainTextO = crypto:block_decrypt(des3_cbc,
     [hexstr2bin("0123456789abcdef"), 
      hexstr2bin("fedcba9876543210"),
      hexstr2bin("0f2d4b6987a5c3e1")],
     hexstr2bin("1234567890abcdef"),
     CipherText),
    PlainHexStr = bin_to_hexstr(PlainTextO),
    io:format("[line:~w]~w~n", [?LINE, PlainHexStr]),
    io:format("[line:~w]~w~n", [?LINE, PlainTextO]).
hexstr2bin 参考 otp_src_19.0\lib\crypto\test

bin_to_hexstr 参考 http://www.cnblogs.com/me-sa/p/erlang_apns.html
posted @ 2016-09-18 17:47  某甲  阅读(413)  评论(0)    收藏  举报