在使用openSSL库时,我遇到了EVP_EncryptFinal_ex的问题. 具体地说,它失败并出现致命错误./crypto/evp/evp_enc.c(348)OpenSSL内部错误,断言失败:b = sizeof ctx - 每次都是buf,不依赖于算法(aes或des). 这是我
具体地说,它失败并出现致命错误./crypto/evp/evp_enc.c(348)OpenSSL内部错误,断言失败:b< = sizeof ctx - >每次都是buf,不依赖于算法(aes或des).
这是我的代码.它尽可能简化.
procedure AESTest; var key : TBytes; keyLen : Integer; dataIn : string; dataOut : TBytes; inLen, outLen, resLen : integer; // Context of an algorithm pointer e_ctx : Pointer; begin // 256 bit key keyLen := 32; setlength(key, KeyLen); RAND_bytes(@(key[0]), KeyLen); // Input data to encrypt dataIn := 'Simple data of 29 bits length'; inLen := length(dataIn); // Init ctx e_ctx := EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_init(e_ctx); EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc, nil, @key[0], nil); // Prepare ouput buf in order to openSSL docs outLen := inLen + EVP_CIPHER_CTX_block_size(e_ctx) - 1; setlength(dataOut, outLen); EVP_EncryptUpdate(e_ctx, @dataOut[0], outLen, @dataIn[1], inLen); EVP_EncryptFinal_ex(e_ctx, @dataOut[outLen], resLen); outLen := outLen + resLen; setlength(dataOut, outLen); // ... here goes decryption part but it does not matter now end;
准确地说,使用的进口:
const LIB_DLL_NAME = 'libeay32.dll'; type PEVP_CIPHER_CTX : Pointer; PEVP_CIPHER : Pointer; function EVP_CIPHER_CTX_new : PEVP_CIPHER_CTX; cdecl; external LIB_DLL_NAME; procedure EVP_CIPHER_CTX_init(a: PEVP_CIPHER_CTX); cdecl; external LIB_DLL_NAME; function EVP_aes_256_cbc : PEVP_CIPHER_CTX; cdecl; external LIB_DLL_NAME; function RAND_bytes(Arr : PByte; ArrLen : integer) : integer; cdecl; external LIB_DLL_NAME; function EVP_CIPHER_CTX_block_size(ctx: PEVP_CIPHER_CTX): integer; cdecl; external LIB_DLL_NAME; function EVP_EncryptInit_ex(ctx: PEVP_CIPHER_CTX; cipher_type: PEVP_CIPHER; Engine : Pointer; key: PByte; iv: PByte): integer; cdecl; external LIB_DLL_NAME; function EVP_EncryptUpdate(ctx: PEVP_CIPHER_CTX; data_out: PByte; var outl: integer; data_in: PByte; inl: integer): integer; cdecl; external LIB_DLL_NAME; function EVP_EncryptFinal_ex(ctx: PEVP_CIPHER_CTX; data_out: PByte; var outl: integer): integer; external LIB_DLL_NAME;
我实际上试图读取源代码(evp_enc.c)并找到断言:
OPENSSL_assert(b <= sizeof ctx->buf);
这里b是当前密码的块的大小.这个断言是有道理的,但我仍然无法弄清楚它在代码中是如何失败的.
我试图在几天内解决这个问题,我会很感激任何建议.
更新:以下是evp_enc.c中的两行:
b=ctx->cipher->block_size; OPENSSL_assert(b <= sizeof ctx->buf);
根据代码,b是当前密码的块大小,对于aes_256_cbc,它是16位长.
问题在于您声明函数EVP_EncryptFinal_ex.你应该添加cdecl指令(就像在所有其他函数中一样).所以,新的声明将是:
function EVP_EncryptFinal_ex(ctx: PEVP_CIPHER_CTX; data_out: PByte; var outl: integer): integer; cdecl; external LIB_DLL_NAME;