erlang 加密解密

来源:互联网 发布:淘宝浏览单app软件 编辑:程序博客网 时间:2024/06/03 21:52

在最近的对接项目中用到了erlang的加解密, 折腾了一番,现记录如下。


url 编码:

to_hex(X) when X >9 ->    X + 55;to_hex(X) ->    X + 48.

url_encode(Url, IsSignSrc) ->    lists:foldl(fun(E,Result) ->        case (E >= $0 andalso E =< $9)            orelse (E >= $A andalso E =< $Z)            orelse (E >= $a andalso E =< $z)            orelse E =:= $-            orelse E=:= $_            orelse  E =:=$.            orelse ( IsSignSrc =:= 1 andalso E =:= $~) of            true ->                Result ++ [E];            _ ->                Result ++ lists:concat([[$%],[to_hex(E bsr 4)], [to_hex(E rem 16)]])        end                         end, [], Url).

url 解码:

from_hex(X) when X >= $A andalso X =< $Z ->    X - $A + 10;from_hex(X) when X >= $a andalso X =< $z ->    X - $a + 10;from_hex(X) when X >= $0 andalso X =< $9 ->    X - $0;from_hex(X) ->    X.

url_decode([], UrlNew) ->    UrlNew;url_decode( [$%,High, Low | Url], UrlNew) ->        url_decode(Url, UrlNew ++ [from_hex(High) * 16 + from_hex(Low)]);url_decode([H| Url], UrlNew) ->    url_decode(Url, UrlNew ++ [H]).

sha 编码:

crypto:hmac(sha, AppKey, RawData)
返回值为binary格式,调用crypto先关函数之前确保crypto application已经启动

base64 编码:

base64:encode_to_string(Sig) 返回字符串
base64:encode(Sig) 返回binary数据


aes_cbc128 编解码:

crypto:block_encrypt(aes_cbc128, Key, Ivec, Data) Key,IVec, Data 的长度为单个block的长度(即16),注意数据补齐
crypto:block_decrypt(aes_cbc128, Key, Ivec, RawData) 注意移除补齐的数据

 






原创粉丝点击