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( )); } }
时间: 2024-11-05 20:38:27