How to check password for pkcs # 12 certificate (.PXF) using openssl C API?

I have a .pxf certificate (AFAIK PKCS # 12). How can I confirm this password for this certificate using the openssl API?

+3
source share
2 answers

One approach to finding answers like this is to find an OpenSSL utility that performs the same functions as you. In this case, you can use the pkcs12 utility that comes with OpenSSL to verify the password.

The command to check the pfx file is as follows:

openssl pkcs12 -in mypfx.pfx -noout

With this information, you can look at its Source Code ( {openssl_src}/apps/pkcs12.c) to see how they do it.

, PKCS12_verify_mac . , :

if( PKCS12_verify_mac(p12, NULL, 0) )
{
    printf("PKCS12 has no password.\n");
}

, , , :

if( PKCS12_verify_mac(p12, password, -1) )
{
    printf("PKCS12 password matches.\n");
}

OpenSSL PKCS12 openssl/demos/pkcs12. pkread.c pfx .

EVP_PKEY *pkey;
X509 *cert;
STACK_OF(X509) *ca = NULL;

if (!PKCS12_parse(p12, password, &pkey, &cert, &ca)) {
    fprintf(stderr, "Error parsing PKCS#12 file\n");
    ERR_print_errors_fp(stderr);
    exit(1);
}

, gcc -std=c99 verifypfx.c -o verifypfx -lcrypto:

#include <stdio.h>
#include <errno.h>
#include <openssl/pkcs12.h>
#include <openssl/err.h>

int main(int argc, char *argv[])
{
        const char *password = "mypassword";
        PKCS12 *p12;

        // Load the pfx file.
        FILE *fp = fopen("mypfx.pfx", "rb");
        if( fp == NULL ) { perror("fopen"); return 1; }
        p12 = d2i_PKCS12_fp(fp, NULL);
        fclose(fp);

        OpenSSL_add_all_algorithms();
        ERR_load_PKCS12_strings();

        if( p12 == NULL ) { ERR_print_errors_fp(stderr); exit(1); }

        // Note:  No password is not the same as zero-length password.  Check for both.
        if( PKCS12_verify_mac(p12, NULL, 0) )
        {
                printf("PKCS12 has no password.\n");
        }
        else if( PKCS12_verify_mac(p12, password, -1) )
        {
                printf("PKCS12 password matches.\n");
        }
        else
        {
                printf("Password not correct.\n");
        }

        return 0;
}
+5

PKCS12_verify_mac(). .

FILE* f = fopen("myfile.pfx", "rb");
PKCS12* p12 = d2i_PKCS12_fp(f, NULL);
fclose(f);
if (!PKCS12_verify_mac(p12, (char*)"mypassword", strlen("mypassword")))
{
   // handle failure
}
+1

Source: https://habr.com/ru/post/1785155/


All Articles