Extracting private key in java

陌路散爱 提交于 2019-12-10 10:15:09

问题


I have certificate created using java class CertAndKeyGen and X500Name and I am able to generate the certificate which is in byte array. Now I want the private key I used in certificate and convert it into readable format. Below is the code I used to create the certificate,

    CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null); 
    X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);
    keypair.generate(keysize);
    PrivateKey privKey = keypair.getPrivateKey();
    PKCS10 certReq = keypair.getCertRequest(x500Name);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);
    keyStore.setKeyEntry(alias, privKey, keyStorePassword.toCharArray(), chain);                    
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(bs);
    certReq.print(ps);
    byte[] certReqPrintable = bs.toByteArray(); 

I have got no clues, please help me to go in right direction to get private key and convert it into readable format. Thanks in advance.


回答1:


If you want to save the private key to a file use

byte[] privateKeyBytes = privKey.getEncoded();

This returns the key in DER encoded (binary) format.

In case you want just to display the contained values on the console just print it using toString():

System.out.println(privKey);



回答2:


BouncyCastle has the useful PEMWriter class that you can use to write the private key to a file in PEM format (this is what tools like OpenSSH and curl expect).

PEMWriter privatepemWriter = new PEMWriter(new FileWriter(filename)));
privatepemWriter.writeObject(privKey);
privatepemWriter.close();

Otherwise you can just save the byte array from the private key which is the DER format also used by many tools.

Finally you can write it to a JKS keystore used by other java programs using this:

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null);
keyStore.setKeyEntry("some alias", privKey, somePassword.toCharArray(), chain[0]));
FileOutputStream fos = new FileOutputStream(filename);
keyStore.store(fos, somePassword.toCharArray());
fos.close();


来源:https://stackoverflow.com/questions/11030195/extracting-private-key-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!