EVP cipher

    Symmetric encryption with EVP Steps As follows: notes that cipher buffer length should be one block size longer.

  // 1, initial the CTX truct

  EVP_CIPHER_CTX_init(&ctx);

 

  // 2, get the algorithm

  cipher = EVP_des_cbc();

 

  // 3, initial encrypt

  // the third parameter shows that we don't use hardware engine

  if(!EVP_EncryptInit_ex(&ctx,cipher,NULL,key,iv))

     return FALSE;

 

  // 4, set padding mode, 0 stands for EVP_CIPH_NO_PADDING

  // if set 1, just use default PKCS1 padding, add the number the last blob short for. Add n bytes which values n to make the length the multiply of cipher block.

  EVP_CIPHER_CTX_set_padding(&ctx,0);

 

  // 5, update encrypt, new we input the whole length of plain data.

  if(!EVP_EncryptUpdate(&ctx, bOutBuf,&outl, bPlaindata, iPlaindata_len))

     return FALSE;

 

  // 6, final encrypt

  if(!EVP_EncryptFinal_ex(&ctx, bOutBuf + outl,&outl2))

     return FALSE;

 

  // 7, fix the chipper data length

  iChipperLen = outl + outl2;

 

decrypt is as the same way of encrypt, just note that decrypt buffer contain the padding data, just copy the out length plain data.

About padding, if don’t set padding, the plain data length must be the multiple of block size, or else the EVP_EncryptUpdate() will encrypt length - length % bolbSize, but EVP_EncryptFinal_ex() will return FALSE.

 

你可能感兴趣的:(Algorithm,null,buffer,input,encryption)