只需编写测试功能并报告参数错误

时间:2019-07-03 11:11:59

标签: erlang aes

这是我的代码,主要使用crypto应用程序:

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

test()->        
    application:start(crypto),
    Type = aes_cbc128,      
    Key = <<"3R9p7eUVAw31ULQG">>,
    IVec = <<0:128>>,
    crypto:block_encrypt(Type, Key, IVec, {<<"M2UsytYCU4FD70y5">>,<<"123456">>}).

2 个答案:

答案 0 :(得分:1)

您正在混淆两个功能签名。这对我有用:

test()->        
    application:start(crypto),

    Type = aes_gcm, 
    %Type = aes_cbc128,      
    Key = <<"3R9p7eUVAw31ULQG">>,
    IVec = <<0:128>>,
    crypto:block_encrypt(Type, Key, IVec, {<<"M2UsytYCU4FD70y5">>,<<"123456">>}).

在外壳中:

~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3  (abort with ^G)

1> c(my).    
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

2> my:test().
{<<"5%2âJ*">>,
 <<217,210,215,102,59,40,188,57,156,163,170,158,10,239,
   135,85>>}

docs给出以下功能定义:

block_encrypt(Type, Key, Ivec, PlainText)

在该函数子句中,PlainText必须是类型iodata(),无论iodata()是什么,它都是 not 元组。

如果您为第4个参数指定两个元素元组,那么您将匹配此函数子句:

block_encrypt(AeadType, Key, Ivec, {AAD, PlainText})

并且,在该函数子句中,AeadType的类型为aead_cipher(),该字符在页面上的其他位置定义为:

aead_cipher() = aes_gcm | chacha20_poly1305

换句话说,aes_cbc128是变量AeadType的“错误参数”。

请注意,在定义部分aead_cipher()的文档部分中没有格式设置-所有类型定义都以一个大类型定义的形式一起运行,因此很难知道要怎么做上。它应该看起来像这样:

stream_cipher() = rc4 | aes_ctr 

block_cipher() = aes_cbc | aes_cfb8 | aes_cfb128 | aes_ige256 | blowfish_cbc 
     | blowfish_cfb64 | des_cbc | des_cfb | des3_cbc | des3_cfb | des_ede3 | rc2_cbc 

aead_cipher() = aes_gcm | chacha20_poly1305 
stream_key() = aes_key() | rc4_key() 
block_key() = aes_key() | blowfish_key() | des_key()| des3_key() 
aes_key() = iodata()

答案 1 :(得分:-1)

函数crypto:bloc_encrypt / 4接受几组参数:

  

block_encrypt(Type,Key,Ivec,PlainText)-> CipherText |错误

     

block_encrypt(AeadType,Key,Ivec,{AAD,PlainText})-> {CipherText,CipherTag} |错误

     

block_encrypt(aes_gcm | aes_ccm,Key,Ivec,{AAD,PlainText,TagLength})-> {CipherText,CipherTag} |错误

在代码中,您选择了第二个。在这种情况下,必须将“ aead_cypher”用作第一个参数

  

aead_cipher()= aes_gcm | aes_ccm | chacha20_poly1305

如果要使用Type参数,则它是必须仅将纯文本作为最后一个参数而不是{AAD,PlainText}使用的第一组参数。顺便说一句,您在示例中选择的类型不正确,我想您想要aes_128_cbc。

1> application:start(crypto). 
ok
2> Type = aes_128_cbc.
aes_128_cbc
3> Key = <<"3R9p7eUVAw31ULQG">>.
<<"3R9p7eUVAw31ULQG">>
4> IVec = <<0:128>>.
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>
5> Aes = aes_gcm.
aes_gcm
6> crypto:block_encrypt(Type, Key, IVec, <<"1234567890123456789">>).
<<242,220,105,109,252,235,224,216,46,180,149,145,37,129,
  35,194>>
7>  crypto:block_encrypt(Aes, Key, IVec, {<<"M2UsytYCU4FD70y5">>,<<"1234567890123456789">>}).   
{<<53,37,50,226,74,42,229,68,133,9,224,144,125,216,121,49,
   13,225,4>>,
 <<188,96,67,137,208,176,32,237,177,144,147,152,84,130,
   225,98>>}
8>