keytool是一個Java資料證書的管理工具,
keytool将密鑰(key)和證書(certificates)存在一個稱為keystore的檔案中在keystore裡,
包含兩種資料:
密鑰實體(Key entity)——密鑰(secret key)又或者是私鑰和配對公鑰(采用非對稱加密)
可信任的證書實體(trusted certificate entries)——隻包含公鑰
ailas(别名)每個keystore都關聯這一個獨一無二的alias,這個alias通常不區分大小寫
下面給出一個java 調用 keytool 生成keystore 和 cer 證書的例子測試:
[java] view plain copy
- public class ExportCertFormKeystore {
- public void execCommand(String[] arstringCommand) {
- for (int i = 0; i < arstringCommand.length; i++) {
- System.out.print(arstringCommand[i] + " ");
- }
- try {
- Runtime.getRuntime().exec(arstringCommand);
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public void execCommand(String arstringCommand) {
- try {
- Runtime.getRuntime().exec(arstringCommand);
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public void genkey() {
- String[] arstringCommand = new String[] {
- "cmd ", "/k",
- "start", // cmd Shell指令
- "keytool",
- "-genkey", // -genkey表示生成密鑰
- "-validity", // -validity指定證書有效期(機關:天),這裡是36000天
- "36500",
- "-keysize",// 指定密鑰長度
- "1024",
- "-alias", // -alias指定别名,這裡是ss
- "ss",
- "-keyalg", // -keyalg 指定密鑰的算法 (如 RSA DSA(如果不指定預設采用DSA))
- "RSA",
- "-keystore", // -keystore指定存儲位置,這裡是d:/demo.keystore
- "d:/demo.keystore",
- "-dname",// CN=(名字與姓氏), OU=(組織機關名稱), O=(組織名稱), L=(城市或區域名稱),
- // ST=(州或省份名稱), C=(機關的兩字母國家代碼)"
- "CN=(SS), OU=(SS), O=(SS), L=(BJ), ST=(BJ), C=(CN)",
- "-storepass", // 指定密鑰庫的密碼(擷取keystore資訊所需的密碼)
- "123456",
- "-keypass",// 指定别名條目的密碼(私鑰的密碼)
- "123456",
- "-v"// -v 顯示密鑰庫中的證書詳細資訊
- };
- execCommand(arstringCommand);
- }
- public void export() {
- String[] arstringCommand = new String[] {
- "cmd ", "/k",
- "start", // cmd Shell指令
- "keytool",
- "-export", // - export指定為導出操作
- "-keystore", // -keystore指定keystore檔案,這裡是d:/demo.keystore
- "d:/demo.keystore",
- "-alias", // -alias指定别名,這裡是ss
- "ss",
- "-file",//-file指向導出路徑
- "d:/demo.cer",
- "-storepass",// 指定密鑰庫的密碼
- "123456"
- };
- execCommand(arstringCommand);
- }
- }
JUnit測試用例:
[java] view plain copy
- import org.junit.Test;
- public class ExportCertFormKeystoreTest {
- @Test
- public void genkeyTest() {
- //生成密鑰測試
- new ExportCertFormKeystore().genkey();
- }
- @Test
- public void exportTest() {
- //導出證書檔案測試
- new ExportCertFormKeystore().export();
- }
- }
運作測試用例之後,在D盤的根目錄下面會生成兩個檔案:
demo.keystore
demo.cer