在EVP_EncryptFinal_ex,delphi期间openssl错误“断言失败”

时间:2013-03-12 00:39:52

标签: delphi openssl assertions

在使用openSSL库时,我遇到了EVP_EncryptFinal_ex的问题。 具体地说,它每次失败都会导致致命错误./crypto/evp/evp_enc.c(348) OpenSSL internal error, assertion failed: 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位长。

1 个答案:

答案 0 :(得分:2)

问题出在你的函数EVP_EncryptFinal_ex的声明中。您应该添加cdecl指令(与所有其他函数一样)。 所以,新的声明将是:

function EVP_EncryptFinal_ex(ctx: PEVP_CIPHER_CTX; data_out: PByte; var outl: integer): integer; cdecl; external LIB_DLL_NAME;