Question

I need to make two pieces of software interoperate. One is a webservice in .NET which returns the raw binary data of an instance of X509Certificate2, as Base64 encoded. The other is an android app which can use OpenSSL to consume the binary certificate received from the webservice.

However OpenSSL always replies that the data is not a valid certificate format. I've tried wrapping the Base64 string in the applicable PEM header and footer but it had no effect.

Is there anybody who has any experience with this kind of interoperability?

Was it helpful?

Solution

This method converts X509Certificate2 to PEM format in C#:

public static string ConvertToPEM(X509Certificate2 cert)
{
    if (cert == null)
        throw new ArgumentNullException("cert");

    string base64 = Convert.ToBase64String(cert.RawData).Trim();

    string pem = "-----BEGIN CERTIFICATE-----" + Environment.NewLine;

    do
    {
        pem += base64.Substring(0, 64) + Environment.NewLine;
        base64 = base64.Remove(0, 64);
    }
    while (base64.Length > 64);

    pem += base64 + Environment.NewLine + "-----END CERTIFICATE-----";

    return pem;
}

This method uses OpenSSL to parse PEM encoded certificate in C:

X509* parse_pem_cert(const char* buffer, int buffer_len)
{
    X509* cert = NULL;
    BIO* bio = NULL;

    if ((NULL == buffer) || (buffer_len < 1))
        return NULL;

    bio = BIO_new_mem_buf((char *) buffer, buffer_len);
    if (NULL == bio)
        return NULL;

    cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
    if (NULL == cert)
    {
        BIO_free(bio);
        return NULL;
    }

    BIO_free(bio);
    return cert;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top