Generating RSA keys in PKCS#1 format in Java

前端 未结 6 660
有刺的猬
有刺的猬 2020-11-28 08:33

When I generate an RSA key pair using the Java API, the public key is encoded in the X.509 format and the private key is encoded in the PKCS#8 format. I\'m looking to encod

6条回答
  •  囚心锁ツ
    2020-11-28 08:56

    I wrote a C programme to convert pkcs8 private key to pkcs1. It works!

    /*****************************************
        convert pkcs8 private key file to pkcs1
    
        2013-1-25   Larry Wu     created
     ****************************************/
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #include 
    #include  
    #include  
    #include 
    #include 
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    
    #define MY_TRACE_ERROR printf
    
    
    /*
        gcc -Wall -o pkcs_8to1 pkcs_8to1.cpp -g -lstdc++ -lcrypto -lssl
    */
    int main(int argc, char **argv)
    {
        EVP_PKEY * pkey = NULL;
        string kin_fname;
        FILE *kin_file = NULL;
        string kout_fname;
        FILE *kout_file = NULL;
    
        // param
        if(argc != 3)
        {
            printf("Usage: %s  \n", argv[0]);
            return 1;
        }
    
        kin_fname = argv[1];
        kout_fname = argv[2];
    
    
        // init
        OpenSSL_add_all_digests();
        ERR_load_crypto_strings();
    
        // read key
        if((kin_file = fopen(kin_fname.c_str(), "r")) == NULL)
        {
            MY_TRACE_ERROR("kin_fname open fail:%s\n", kin_fname.c_str());
            return 1;
        }
    
        if ((pkey = PEM_read_PrivateKey(kin_file, NULL, NULL, NULL)) == NULL) 
        {
            ERR_print_errors_fp(stderr);
            MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
            fclose(kin_file);
            return 2;
        }
    
        // write key
        if((kout_file = fopen(kout_fname.c_str(), "w")) == NULL)
        {
            MY_TRACE_ERROR("kout_fname open fail:%s\n", kout_fname.c_str());
            return 1;
        }
    
        if (!PEM_write_PrivateKey(kout_file, pkey, NULL, NULL, 0, NULL, NULL)) 
        {
            ERR_print_errors_fp(stderr);
            MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
            fclose(kout_file);
            return 2;
        }
    
        // clean
        fclose(kin_file);
        fclose(kout_file);
        EVP_PKEY_free(pkey);
    
        return 0;
    }
    

提交回复
热议问题