Thomas Klier
Thomas Klier

Reputation: 469

Decode ASN.1 with Crypto++

I try to convert the ASN.1 sequence "AgER" to an CryptoPP::Integer.

#include <crypto++/asn.h>
#include <iostream>

int main(int, char*[])
{
    std::string base64{"AgER"};

    CryptoPP::StringSource s{base64, true};
    CryptoPP::BERSequenceDecoder d{s};
    CryptoPP::Integer i;
    i.BERDecode(d);

    std::cout << i.ConvertToLong() << std::endl;
}

This throws an exception of type CryptoPP::BERDecodeErr with message "BER decode error".

Various ASN.1 tools can parse the string without problem: https://lapo.it/asn1js/#AgER

Upvotes: 1

Views: 557

Answers (1)

Thomas Klier
Thomas Klier

Reputation: 469

I found out that Crypto++ expects binary data, not Base64 encoded. So I had to decode this before.

Here the working solution;

#include <crypto++/asn.h>
#include <crypto++/base64.h>
#include <iostream>

int main(int, char*[])
{
    std::string base64{"AgER"};

    std::string decoded;
    CryptoPP::StringSource{base64, true, new CryptoPP::Base64Decoder{new CryptoPP::StringSink{decoded}}};

    CryptoPP::StringSource s{decoded, true};
    CryptoPP::Integer i;
    i.BERDecode(s);

    std::cout << i.ConvertToLong() << std::endl;
}

Upvotes: 2

Related Questions