M
M
Maxim Barulin2014-12-09 11:24:55
Erlang
Maxim Barulin, 2014-12-09 11:24:55

How to encode/decode text in Erlang?

Good day,% Habrauser%!
Need to encode/decode plain text using AES-256 encryption. The simplest code:

crypto:start(),
Key = <<"aj2lbj2k4kljaj3k2l4k3l4kk2l3jj32">>, 
IVec = <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>, 
Text = <<"testtesttesttesttesttest">>, 
  
Enc = crypto:block_encrypt(aes_cbc256, Key, IVec, Text),
Res = crypto:block_decrypt(aes_cbc256, Key, IVec, Enc),
io:format("Res: ~s~n", [binary_to_list(Res)]).

gives an error message:
** exception error: bad argument
     in function  crypto:aes_cbc_crypt/4
        called as crypto:aes_cbc_crypt(<<"aj2lbj2k4kljaj3k2l4k3l4kk2l3jj32">>,
                                       <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>,
                                       <<"testtesttesttesttesttest">>,true)

After a bit of debugging, I found that the problem is only for a string less than 32 characters. I am not strong in cryptography. It is possible to make somehow that the text of any length is encoded/decoded.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita S., 2014-12-09
@Slavenin999

I suppose you can replace the missing number of characters with zeros.

M
Maxim Sokhatsky, 2015-01-29
@5HT

AES-CBC encryption with HMAC can be used from the N2O standard library:

pickle(Data) ->
    Message = term_to_binary({Data,now()}),
    Padding = size(Message) rem 16,
    Bits = (16-Padding)*8, Key = secret(), IV = crypto:rand_bytes(16),
    Cipher = crypto:block_encrypt(aes_cbc128,Key,IV,<<Message/binary,0:Bits>>),
    Signature = crypto:hmac(sha256,Key,<<Cipher/binary,IV/binary>>),
    base64:encode(<<IV/binary,Signature/binary,Cipher/binary>>).

secret() -> wf:config(n2o,secret,<<"ThisIsClassified">>).

depickle(PickledData) ->
    try Key = secret(),
        Decoded = base64:decode(wf:to_binary(PickledData)),
        <<IV:16/binary,Signature:32/binary,Cipher/binary>> = Decoded,
        Signature = crypto:hmac(sha256,Key,<<Cipher/binary,IV/binary>>),
        {Data,_Time} = binary_to_term(crypto:block_decrypt(aes_cbc128,Key,IV,Cipher),[safe]),
        Data
    catch E:R -> wf:info(?MODULE,"Depicke Error: ~p",[{E,R}]), undefined end.

https://github.com/5HT/n2o/blob/master/src/handler...
pickle/1 and depickle/1 have been verified: https://github.com/5HT/n2o/issues/63

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question