Search code examples
c++base64crypto++bigint

How to convert base64 to Integer in Crypto++?


I use Crypto++ library. I have a base64 string saved as CString. I want to convert my string to Integer. actually this base64 built from an Integer and now i want to convert to Integer again.but two Integer not equal.in the other words second Integer not equal with original Integer.

Base64Decoder bd;
CT2CA s(c);
std::string strStd(s);

bd.Put((byte*)strStd.data(), strStd.size());
bd.MessageEnd();

word64 size = bd.MaxRetrievable();
vector<byte> cypherVector(size);

string decoded;
if (size && size <= SIZE_MAX)
{
    decoded.resize(size);
    bd.Get((byte*)decoded.data(), decoded.size());
}

Integer cipherMessage((byte*)decoded.data(), decoded.size());

Solution

  • string decoded;
    if (size && size <= SIZE_MAX)
    {
        decoded.resize(size);
        bd.Get((byte*)decoded.data(), decoded.size());
    }
    

    You have a string called decoded, but you never actually decode the data by running it through a Base64Decoder.

    Use something like the following. I don't have a MFC project handy to test, so I'm going to assume you converted the CString to a std::string.

    // Converted from Unicode CString
    std::string str;
    
    StringSource source(str, true, new Base64Decoder);
    Integer value(val, source.MaxRetrievable());
    std::cout << std::hex << value << std::endl;
    

    The StringSource is a BufferedTransformation. The Integer constructor you are using is:

    Integer (BufferedTransformation &bt, size_t byteCount, Signedness sign=UNSIGNED, ByteOrder order=BIG_ENDIAN_ORDER)
    

    In between the StringSource and the Integer is the Base64Decoder. its a filter that decodes the string on the fly. So data flows from the source (StringSource) to the sink (Integer constructor).

    Also see Pipelines on the Crypto++ wiki.