4

在使用 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 位长。

4

1 回答 1

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;
于 2013-03-13T09:08:10.407 回答