//------------------------------------------------------------------------- // Function Name :EncodeBase64 // Parameter(s) :LPBYTE *pBuf The binary buffer // :ULONG ulSize size // Return :CString the result // Memo :encoding the binary buffer into Base64 string //------------------------------------------------------------------------- CString CXml::Base64Encode(LPBYTE pBuf, ULONG ulSize) { ASSERT( m_pDoc != NULL ); ASSERT( pBuf != NULL ); CString strRet = _T(""); try { MSXML2::IXMLDOMElementPtr pElement = NULL; pElement = m_pDoc->createElement( _bstr_t(_T("Base64")) ); ASSERT( pElement != NULL ); HRESULT hr = S_OK; hr = pElement->put_dataType( _bstr_t(_T("bin.base64")) ); ASSERT( SUCCEEDED(hr) ); SAFEARRAY * pAry = SafeArrayCreateVector( VT_UI1, 0L, ulSize); ::memcpy( pAry->pvData, pBuf, ulSize); VARIANT var; VariantInit(&var); var.parray = pAry; var.vt = VT_ARRAY | VT_UI1; pElement->nodeTypedValue = var; BSTR bstr = NULL; hr = pElement->get_text( &bstr ); ASSERT( SUCCEEDED(hr) ); strRet = (LPCTSTR)_bstr_t( bstr, true); if( bstr != NULL ) { SysFreeString(bstr); bstr = NULL; } RELEASE_PTR(pElement); } catch ( _com_error e ) { TRACE( _T("CXml::Base64Encode failed:%s\n"), e.ErrorMessage()); ASSERT( FALSE ); } return strRet; }
//------------------------------------------------------------------------- // Function Name :Base64Decode // Parameter(s) :LPCTSTR pszIn Base64编码 // :LPBYTE pBuf 缓冲区首地址 // :ULONG &ulSize 缓冲区大小 // Return :BOOL // Memo :将Base64编码解码为二进制形式 // 注意!此函数的缓冲区需要在函数调用完后删除 //------------------------------------------------------------------------- BOOL CXml::Base64Decode(LPCTSTR pszIn, LPBYTE& pBuf, LONG& lSize) { ASSERT(m_pDoc != NULL); try { MSXML2::IXMLDOMElementPtr pElement = NULL; pElement = m_pDoc->createElement(_bstr_t(_T("Base64"))); ASSERT(pElement != NULL); HRESULT hr = S_OK; hr = pElement->put_dataType(_bstr_t(_T("bin.base64"))); ASSERT(SUCCEEDED(hr)); hr = pElement->put_text(CComBSTR(pszIn)); ASSERT(SUCCEEDED(hr)); hr = SafeArrayGetUBound(pElement->nodeTypedValue.parray, 1, &lSize); ASSERT(SUCCEEDED(hr)); lSize ++; pBuf = new BYTE[lSize]; memset(pBuf, 0, lSize); memcpy(pBuf, LPVOID(pElement->nodeTypedValue.parray->pvData), lSize); RELEASE_PTR(pElement); } catch (_com_error e) { TRACE(_T("CXml::Base64Decode 发生异常:%s\n"), e.ErrorMessage()); ASSERT(FALSE); return FALSE; } return TRUE; }