Keystore是一個密碼保護的檔案,存放私密金鑰和認證。可以通過JDK內建的keytool工具產生。
但是keytool工具,並沒有提供方便的方法,從keystore檔案中到處私密金鑰和認證。
所以可以通過JDK提供的java.security.KeyStore
類來編碼完成相關工作。
參見:
http://www.anandsekar.com/2006/01/19/exporting-the-private-key-from-a-jks-keystore/
<br /> import java.io.File;<br /> import java.io.FileInputStream;<br /> import java.io.FileWriter;<br /> import java.security.Key;<br /> import java.security.KeyPair;<br /> import java.security.KeyStore;<br /> import java.security.KeyStoreException;<br /> import java.security.NoSuchAlgorithmException;<br /> import java.security.PrivateKey;<br /> import java.security.PublicKey;<br /> import java.security.UnrecoverableKeyException;<br /> import java.security.cert.Certificate;</p><p> import sun.misc.BASE64Encoder; </p><p> public class ExportPrivateKey {<br /> private File keystoreFile;<br /> private String keyStoreType;<br /> private char[] password;<br /> private String alias;<br /> private File exportedFile; </p><p> public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {<br /> try {<br /> Key key=keystore.getKey(alias,password);<br /> if(key instanceof PrivateKey) {<br /> Certificate cert=keystore.getCertificate(alias);<br /> PublicKey publicKey=cert.getPublicKey();<br /> return new KeyPair(publicKey,(PrivateKey)key);<br /> }<br /> } catch (UnrecoverableKeyException e) {<br /> } catch (NoSuchAlgorithmException e) {<br /> } catch (KeyStoreException e) {<br /> }<br /> return null;<br /> }</p><p> public void export() throws Exception{<br /> KeyStore keystore=KeyStore.getInstance(keyStoreType);<br /> BASE64Encoder encoder=new BASE64Encoder();<br /> keystore.load(new FileInputStream(keystoreFile),password);<br /> KeyPair keyPair=getPrivateKey(keystore,alias,password);<br /> PrivateKey privateKey=keyPair.getPrivate();<br /> String encoded=encoder.encode(privateKey.getEncoded());<br /> FileWriter fw=new FileWriter(exportedFile);<br /> fw.write(“—–BEGIN PRIVATE KEY—–/n“);<br /> fw.write(encoded);<br /> fw.write(“/n“);<br /> fw.write(“—–END PRIVATE KEY—–”);<br /> fw.close();</p><p> }</p><p> public static void main(String args[]) throws Exception{<br /> ExportPrivateKey export=new ExportPrivateKey();<br /> export.keystoreFile=new File(args[0]);<br /> export.keyStoreType=args[1];<br /> export.password=args[2].toCharArray();<br /> export.alias=args[3];<br /> export.exportedFile=new File(args[4]);<br /> export.export();<br /> }<br /> }<br />