PEM_read_bio_PrivateKey returns NULL

6.8k Views Asked by At

I have a JSON file containing the private key (downloaded it from Google Developer Console for Service Accounts). For building JWT, when I try to load the private key as a EVP_PKEY structure using PEM_read_bio_PrivateKey(), it returns NULL (an error).

Code

const char *private_key = 
   json_object_get_string(json_object_object_get(token_file_obj, 
                                                   "private_key"));
printf("Private key --> [%s]\n", private_key);

/* Not sure whether this is needed, just added all three in case needed X-D */
OpenSSL_add_all_algorithms();
OpenSSL_add_all_ciphers();
OpenSSL_add_all_digests();

BIO *bio = BIO_new_mem_buf(private_key, (int) sizeof(private_key));
if (bio == NULL) {
    printf("Bio is null **** \n");
    return FAILED_OPERATION;
}

EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, 0, NULL);
if (pkey == NULL) {
    printf("Failed operation error code %d\n", errno);
    return FAILED_OPERATION;
}

Output

Note: I've changed the Private Key copied from Output.

Private key --> [-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFBASCBKYwggSiAgEAAoIBAQC9UzuLuU7z0XTS
aixN0uQSGxxw+Ngbm2CyRr01Fm3Zoi4Df1yoVJKxRLscJgzv4hkVzGXsniUIVuqY
peeZ9VAPdqmx1Oz3w/xPUcy6clINTRgg+/xKUQetuxplN4EY9YuQYp8PVqHO3AiZ
WE+VufX0saITyikMCGvIcNdfEky/Kf7CtniEKw1g0eHzbHdxk06wzYmvHxodVwC0
mf8lQ62uFNvw3t0TVaENm0B64NSL+7uCHPZICxJNW352eKgLxisOgV7v6xIYlFz/
O5xoThkRoychsc338/3Pscqd6HVeQkSG/T4lQTl2TFVwJHEF422d8d9ybXFQ7Xe/
qPbhd2A1AgMBAAECggEACtHDHSLHp4jgiXbOVds3s+4vA5iQ5xD712xR+0LvH6kT
qJ51TlhY8r74B22IPzw3TUbbS0ilWqLm8LbIc8SwYNXZ8EL4ENe3J0xILB6E4GQ3
vQjRe+jCDNRct4ySuNutcGCmcOC1SgZKioLgt3CDZQqytblPm7Oufyutry3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qA==
-----END PRIVATE KEY-----
]
Failed operation error code 0

Things I have tried

  1. Replaced the \n in the private key from JSON file with newline, and compared it with the private key printed using printf(). Both had the same checksum.
  2. Removed the -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- from the private key and tried - Did not work.
0

There are 0 best solutions below