Hi,

Could someone help me... I need to know how to encrypt private key. At
command line I encrypt it (pkey.pem) as below,

  C:\>openssl pkcs8 -in pkey.pem -topk8 -out enc key.pem -v1 PBE-SHA1-3DES

It works perfectly. But how to code them using openssl library? My code as
below... Could someone fix the code, or reply with another one. Program give
message "Error encrypting key". I attach pkey.pem file (private key) which
is the file to be encrypted. Thanks in advance. :(

void main()
{
    char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
    char *passargin = NULL, *passargout = NULL;
    char *infile = "pkey.pem", *outfile = "enckey.pem";
    int topk8 = 1;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM;
    const EVP_CIPHER *cipher = NULL;
    BIO *in = NULL, *out = NULL;
    BIO *bio_err = NULL;
    EVP_PKEY *pkey;
    int p8_broken = PKCS8_OK;  // p8_broken = 0
    PKCS8_PRIV_KEY_INFO *p8inf;
    X509_SIG *p8;
    int pbe_nid = NID_pbeWithMD5AndDES_CBC;  // pbe_nid = 10
    int iter = PKCS12_DEFAULT_ITER;

    pbe_nid=OBJ_txt2nid("PBE-SHA1-3DES");  // pbe_nid = 146

    if (!(in = BIO_new_file(infile, "rb")))
    {  printf("Can't open input file %s\n", infile);
       return;
    }

    if (!(out = BIO_new_file (outfile, "wb")))
    {  printf("Can't open output file %s\n", outfile);
       return;
    }

    if (!app_passwd(bio_err, passargin, passargout, &passin, &passout))
    {  printf("Error getting passwords\n");
       return;
    }

    pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, passin);

    if (!pkey)
    {  printf("Error reading key\n");
       return;
    }

    if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken)))
    {  printf("Error converting key\n");
       return;
    }

    p8pass = "syukri";

    if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,p8pass, strlen(p8pass),NULL, 0,
iter, p8inf)))
    {  printf("Error encrypting key\n");
       return;
    }

    PEM_write_bio_PKCS8(out, p8);
    PKCS8_PRIV_KEY_INFO_free (p8inf);
    EVP_PKEY_free(pkey);
    BIO_free_all(out);
    if(passin) OPENSSL_free(passin);
    if(passout) OPENSSL_free(passout);
}

pkey.pem

Reply via email to