標籤:java 密鑰庫 keystore 管理
1 Java程式列出密鑰庫所有條目
import java.util.*;import java.io.*;import java.security.*;public class ShowAlias{ public static void main(String args[ ]) throws Exception{ String pass="080302"; String name=".keystore"; FileInputStream in=new FileInputStream(name); KeyStore ks=KeyStore.getInstance("JKS"); ks.load(in,pass.toCharArray()); Enumeratione=ks.aliases( ); while( e.hasMoreElements()) { System.out.println(e.nextElement()); } }}
2 Java程式修改密鑰庫口令
import java.io.*;import java.security.*;public class SetStorePass{ public static void main(String args[ ]) throws Exception{ char[ ] oldpass="080302".toCharArray(); char[ ] newpass="123456".toCharArray(); String name=".keystore"; FileInputStream in=new FileInputStream(name); KeyStore ks=KeyStore.getInstance("JKS"); ks.load(in,oldpass); in.close(); FileOutputStream output=new FileOutputStream(name); ks.store(output,newpass); output.close(); }}
3 Java程式修改密鑰庫條目的口令及添加條目
package test;import java.io.*;import java.security.*;import java.security.cert.Certificate;public class SetKeyPass{ public static void main(String args[ ]) throws Exception{ //讀取相關參數 String name=".keystore"; String alias="mykey"; char[ ] storepass="123456".toCharArray(); char[ ] oldkeypass="080302".toCharArray(); char[ ] newkeypass="123456".toCharArray(); //擷取密鑰庫.keystore的KeyStore對象,並載入密鑰庫 FileInputStream in=new FileInputStream(name); KeyStore ks=KeyStore.getInstance("JKS"); ks.load(in,storepass); //擷取別名對應的條目的憑證鏈結 Certificate[ ] cchain=ks.getCertificateChain(alias); //讀取別名對應的條目的私密金鑰 PrivateKey pk=(PrivateKey)ks.getKey(alias,oldkeypass); //向密鑰庫中添加新的條目 ks.setKeyEntry(alias,pk,newkeypass,cchain); in.close(); //將KeyStore對象內容寫入新檔案 FileOutputStream output=new FileOutputStream("333"); ks.store(output,storepass); output.close(); }}
4 Java程式檢驗別名及刪除條目
package test;import java.io.*;import java.security.*;public class DeleteAlias{ public static void main(String args[ ]) throws Exception{ String pass = "123456"; String name = ".keystore"; String alias = "mykey"; FileInputStream in=new FileInputStream(name); KeyStore ks=KeyStore.getInstance("JKS"); ks.load(in,pass.toCharArray()); if (ks.containsAlias(alias)){ ks.deleteEntry(alias); FileOutputStream output=new FileOutputStream(name); ks.store(output,pass.toCharArray()); System.out.println("Alias "+alias+" deleted"); }else{ System.out.println("Alias not exist"); } }}
5 Java程式從密鑰庫直接讀取認證
import java.io.*;import java.security.*;import java.security.cert.Certificate;public class PrintCert2{ public static void main(String args[ ]) throws Exception{ String pass="080302"; String alias="mykey"; String name=".keystore"; FileInputStream in=new FileInputStream(name); KeyStore ks=KeyStore.getInstance("JKS"); ks.load(in,pass.toCharArray()); Certificate c=ks.getCertificate(alias); in.close(); System.out.println(c.toString( )); }}
java程式實現對密鑰庫的管理