mercredi 5 septembre 2018

Using OpenSSL to port Java encryption code

I have the following code implemented in Java. The method takes in a base64 PKCS8 encoded key in the form of a string and spits an RSA private key back (that's my interpretation, I'm new to crypto so please bear with me)

public static PrivateKey getPrivateKey(final String 
 Base64EncodedPkcs8String) {
    PKCS8EncodedKeySpec privateKeySpec = new 
    PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedPkcs8String));

    try {
        return KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec);
    }
    catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException", e);
        return null;
    }
    catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException", e);
        return null;
    }
}

I'm trying to do something similar using OpenSSL:

EVP_PKEY* pPrivateKeyInfo = nullptr;
std::string copy = "\n"; //<-- I don't know if this is right
copy += strBase64EncodedPrivateKey;
copy += "\n"; //<-- or this
auto c_string = copy.c_str();
unsigned char* pszDecodedMessage = nullptr;
size_t stEncodedMessageLength{};

this->DecodeBase64Message(c_string, pszDecodedMessage, &stEncodedMessageLength);

auto pKeybio = BIO_new_mem_buf((void*)(pszDecodedMessage), -1);

if (nullptr == pKeybio)
{
    return nullptr;
}

pPrivateKeyInfo = PEM_read_bio_PrivateKey(pKeybio, &pPrivateKeyInfo, nullptr, nullptr);

if (nullptr == pPrivateKeyInfo)
{
    return nullptr;
}

The call to PEM_read_bio_PrivateKey always fails. I have also tried to use PEM_read_bio_PKCS8_PRIV_KEY_INFO, which also fails.

Does anyone see any glaring issues with this code? Is there a better way to do this? (simpler?)

Aucun commentaire:

Enregistrer un commentaire