现在的位置: 首页 > 综合 > 正文

OPENSSL Base64编码和解码

2013年10月08日 ⁄ 综合 ⁄ 共 1521字 ⁄ 字号 评论关闭

 

BOOL Base64Encode(unsigned char *pData, int nLeng, int linebreaks, char * pOutBufffer, int *pBufferLenth)

{

    int res = FALSE;

    BIO *bmem, *b64;

    BUF_MEM *bptr;

 

    b64 = BIO_new(BIO_f_base64());

    if (!b64) return res;

    if (!linebreaks)

    {

       BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    }

    bmem = BIO_new(BIO_s_mem());

    if (bmem) {

       b64 = BIO_push(b64, bmem);

       if (BIO_write(b64, pData, nLeng)==nLeng)

       {

           (void)BIO_flush(b64);

           BIO_get_mem_ptr(b64, &bptr);

           if (*pBufferLenth > bptr->length)

           {

              memcpy(pOutBufffer, bptr->data, bptr->length);

              pOutBufffer[bptr->length] = 0;

              res = TRUE;

           }

           *pBufferLenth = bptr->length + 1;

       }

    }

 

    BIO_free_all(b64);

    return res;

}

 

BOOL Base64Decode(char *pData, int nLeng, int linebreaks, unsigned char * pOutBufffer, int *pBufferLenth)

{

    int res = FALSE;

    BIO *bmem;

    BIO *b64;

    if (nLeng == 0)

       nLeng = strlen(pData);

    int nMaxLen=(nLeng*6+7)/8;

    int nMiniLen;

    unsigned char *buf = new unsigned char[nMaxLen];

    if (buf)

    {

       b64 = BIO_new(BIO_f_base64());

       if (b64)

       {

           if (!linebreaks)

           {

              BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

           }

           bmem = BIO_new_mem_buf((char*)pData, nLeng);

           b64 = BIO_push(b64, bmem);

           nMiniLen = BIO_read(b64, buf, nMaxLen);

           if(*pBufferLenth >= nMiniLen)

           {

              memcpy(pOutBufffer, buf, nMiniLen);

              res = TRUE;

           }

           *pBufferLenth = nMiniLen;

           BIO_free_all(b64);

       }

       delete []buf;

    }

    return res;

}

 

抱歉!评论已关闭.