keytool是一個Java數據證書的管理工具,
keytool將密鑰(key)和證書(certificates)存在一個稱為keystore的文件中在keystore里,
包含兩種數據:
密鑰實體(Key entity)——密鑰(secret key)又或者是私鑰和配對公鑰(采用非對稱加密)
可信任的證書實體(trusted certificate entries)——只包含公鑰
ailas(別名)每個keystore都關聯這一個獨一無二的alias,這個alias通常不區分大小寫
下面給出一個java 調用 keytool 生成keystore 和 cer 證書的例子測試:
1 public class ExportCertFormKeystore { 2 3 public void execCommand(String[] arstringCommand) { 4 for (int i = 0; i < arstringCommand.length; i++) { 5 System.out.print(arstringCommand[i] + " "); 6 } 7 try { 8 Runtime.getRuntime().exec(arstringCommand); 9 10 } catch (Exception e) { 11 System.out.println(e.getMessage()); 12 } 13 } 14 public void execCommand(String arstringCommand) { 15 try { 16 Runtime.getRuntime().exec(arstringCommand); 17 18 } catch (Exception e) { 19 System.out.println(e.getMessage()); 20 } 21 } 22 23 /** 24 * 生成密鑰 25 */ 26 public void genkey() { 27 String[] arstringCommand = new String[] { 28 29 "cmd ", "/k", 30 "start", // cmd Shell命令 31 32 "keytool", 33 "-genkey", // -genkey表示生成密鑰 34 "-validity", // -validity指定證書有效期(單位:天),這里是36000天 35 "36500", 36 "-keysize",// 指定密鑰長度 37 "1024", 38 "-alias", // -alias指定別名,這里是ss 39 "ss", 40 "-keyalg", // -keyalg 指定密鑰的算法 (如 RSA DSA(如果不指定默認采用DSA)) 41 "RSA", 42 "-keystore", // -keystore指定存儲位置,這里是d:/demo.keystore 43 "d:/demo.keystore", 44 "-dname",// CN=(名字與姓氏), OU=(組織單位名稱), O=(組織名稱), L=(城市或區域名稱), 45 // ST=(州或省份名稱), C=(單位的兩字母國家代碼)" 46 "CN=(SS), OU=(SS), O=(SS), L=(BJ), ST=(BJ), C=(CN)", 47 "-storepass", // 指定密鑰庫的密碼(獲取keystore信息所需的密碼) 48 "123456", 49 "-keypass",// 指定別名條目的密碼(私鑰的密碼) 50 "123456", 51 "-v"// -v 顯示密鑰庫中的證書詳細信息 52 }; 53 execCommand(arstringCommand); 54 } 55 56 /** 57 * 導出證書文件 58 */ 59 public void export() { 60 61 String[] arstringCommand = new String[] { 62 63 "cmd ", "/k", 64 "start", // cmd Shell命令 65 66 "keytool", 67 "-export", // - export指定為導出操作 68 "-keystore", // -keystore指定keystore文件,這里是d:/demo.keystore 69 "d:/demo.keystore", 70 "-alias", // -alias指定別名,這里是ss 71 "ss", 72 "-file",//-file指向導出路徑 73 "d:/demo.cer", 74 "-storepass",// 指定密鑰庫的密碼 75 "123456" 76 77 }; 78 execCommand(arstringCommand); 79 80 } 81 }
JUnit測試用例:
1 import org.junit.Test; 2 3 public class ExportCertFormKeystoreTest { 4 5 @Test 6 public void genkeyTest() { 7 //生成密鑰測試 8 new ExportCertFormKeystore().genkey(); 9 } 10 @Test 11 public void exportTest() { 12 //導出證書文件測試 13 new ExportCertFormKeystore().export(); 14 } 15 16 }
運行測試用例之后,在D盤的根目錄下面會生成兩個文件:
demo.keystore
demo.cer