EVP cipher

来源:互联网 发布:11房间网络已断开 编辑:程序博客网 时间:2024/05/01 22:06

    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.

 

原创粉丝点击