iT邦幫忙

0

應用系統建置前準備工具 - KeyStoreUtils 金鑰庫工具

  • 分享至 

  • xImage
  •  

KeyStoreUtils 金鑰庫工具類別

概述

KeyStoreUtils 是一個用於管理 Java KeyStore(金鑰庫)的工具類別,提供完整的金鑰庫操作功能,包括建立、讀取、修改密碼、儲存資料與查詢別名等。此類別主要使用 JCEKS 格式的金鑰庫,並提供多種便利方法來處理金鑰庫相關操作。

專案相關程式

  • GlobalConstants

第三方元件(Dependency)

  • org.apache.commons.lang3

主要功能

1. 金鑰庫檔案管理

建立新金鑰庫

// 使用自訂檔名和密碼建立
KeyStoreUtils.createNewKeyStoreFile("custom.keystore", "your_password");

// 使用預設密碼建立
KeyStoreUtils.createNewKeyStoreWithDefaultPassword("custom.keystore");

// 使用預設檔名建立
KeyStoreUtils.createDefaultKeyStoreWithPassword("your_password");

// 使用預設檔名和密碼建立
KeyStoreUtils.createNewKeyStoreWithDefault();

取得金鑰庫實例

// 使用自訂檔名和密碼
KeyStore keyStore = KeyStoreUtils.getKeyStoreFile("custom.keystore", "your_password");

// 使用預設密碼
KeyStore keyStore = KeyStoreUtils.getKeyStoreFile("custom.keystore");

// 使用預設檔名
KeyStore keyStore = KeyStoreUtils.getKeyStore("your_password");

// 使用預設檔名和密碼
KeyStore keyStore = KeyStoreUtils.getKeyStore();

2. 密碼管理

變更金鑰庫密碼

// 變更金鑰庫密碼
KeyStoreUtils.changeKeyStorePassword(
    "keystore.jks",     // 金鑰庫檔名
    "old_password",     // 舊密碼
    "new_password"      // 新密碼
);

3. 別名(Alias)管理

查詢別名清單

// 列出所有別名及其類型
Map<String, String> aliases = KeyStoreUtils.listAllKeyStoreAlias(
    "keystore.jks",    // 金鑰庫檔名
    "your_password"    // 密碼
);

資料存取

// 儲存資料到別名
KeyStoreUtils.setAliasDataToKeyStore(
    "keystore.jks",     // 金鑰庫檔名
    "your_password",    // 密碼
    "alias_name",       // 別名
    "secret_data"       // 要儲存的資料
);

// 讀取別名資料
String data = KeyStoreUtils.getAliasDataFromKeystore(
    "keystore.jks",     // 金鑰庫檔名
    "your_password",    // 密碼
    "alias_name"        // 別名
);

技術特點

  1. 金鑰庫格式

    • 使用 JCEKS 格式(支援較強的加密演算法)
    • 相容 Java 金鑰庫標準
    • 支援多種金鑰類型存儲
  2. 安全性考量

    • 密碼變更時同步更新所有項目
    • 支援 PBE(Password-Based Encryption)
    • 自動處理金鑰項目的保護參數
  3. 資料存取控制

    • 支援三種類型的項目(PrivateKey、SecretKey、TrustedCertificate)
    • 自動檢查金鑰庫存在性
    • 提供安全的資料存取機制

使用注意事項

  1. 檔案管理

    • 操作前確認檔案路徑正確
    • 注意檔案存取權限
    • 建議定期備份金鑰庫檔案
  2. 密碼處理

    • 妥善保管金鑰庫密碼
    • 密碼變更時需要同時更新相關應用
    • 避免使用預設密碼於正式環境
  3. 效能考量

    • 金鑰庫操作較為耗時
    • 建議快取經常使用的資料
    • 避免過於頻繁的讀寫操作

常見問題

  1. 金鑰庫無法開啟

    • 檢查檔案權限
    • 確認密碼正確性
    • 驗證金鑰庫格式
  2. 密碼變更失敗

    • 確保有足夠的寫入權限
    • 檢查舊密碼是否正確
    • 確認所有項目都能正確更新
  3. 資料存取異常

    • 檢查別名是否存在
    • 確認金鑰類型正確
    • 驗證存取權限設定

單元測試範例

以下測試範例示範 KeyStoreUtils 的常見測試場景(示範性):

1. 建立與讀取金鑰庫

@Test
void testCreateAndLoadKeyStore(@TempDir Path tempDir) throws Exception {
   String ksPath = tempDir.resolve("test.keystore").toString();
   String password = "changeit";

   KeyStoreUtils.createNewKeyStoreFile(ksPath, password);
   KeyStore ks = KeyStoreUtils.getKeyStoreFile(ksPath, password);
   assertNotNull(ks);
}

2. 儲存與讀取別名資料

@Test
void testSetAndGetAliasData(@TempDir Path tempDir) throws Exception {
   String ksPath = tempDir.resolve("alias.keystore").toString();
   String password = "pw";
   KeyStoreUtils.createNewKeyStoreFile(ksPath, password);

   KeyStoreUtils.setAliasDataToKeyStore(ksPath, password, "alias1", "secret");
   String data = KeyStoreUtils.getAliasDataFromKeystore(ksPath, password, "alias1");
   assertEquals("secret", data);
}

3. 密碼變更與異常處理

@Test
void testChangePasswordAndError(@TempDir Path tempDir) throws Exception {
   String ksPath = tempDir.resolve("pw.keystore").toString();
   String oldPw = "old";
   String newPw = "new";
   KeyStoreUtils.createNewKeyStoreFile(ksPath, oldPw);

   KeyStoreUtils.changeKeyStorePassword(ksPath, oldPw, newPw);
   // 使用新密碼能讀取
   KeyStore ks = KeyStoreUtils.getKeyStoreFile(ksPath, newPw);
   assertNotNull(ks);

   // 使用錯誤密碼會拋出例外
   assertThrows(Exception.class, () -> KeyStoreUtils.getKeyStoreFile(ksPath, "wrong"));
}

測試說明

  • 建立臨時 keystore 並驗證讀寫
  • 測試別名資料的儲存與回讀
  • 驗證密碼變更流程與錯誤處理

程式碼 KeyStoreUtils.java

package tw.lewishome.webapp.base.utility.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.commons.lang3.StringUtils;

import tw.lewishome.webapp.GlobalConstants;

// * <pre>
// * KeyStoreUtils class.
// * (1) Using OS Command can change the keystore password
// *  $ keyTool -storePasswd -keystore keyStoreSame
// *  Enter keystore password:  <old password>
// *  New keystore password: <new password>
// *  Re-enter new keystore password: <new pass  (2) OS Command to change alias password
// * (1) Using OS Command can change the keystore alias data (password)
// *  $ keyTool -keyPasswd -keystore keyStoreName -alias aliasName
// *  Enter keystore password:
// *  New key password for <aliasName>:
// *  Re-enter new key password for <aliasName>:
// * </pre>
// *

/**
 * KeyStoreUtils 提供一組操作 Java KeyStore 的工具方法,包含建立、讀取、修改密碼、儲存資料、查詢別名等功能。
 *
 * 支援 JCEKS 或 PKCS12 等 KeyStore 類型,並可透過指定檔案路徑與密碼進行操作。
 *
 *
 * 主要功能:
 * <ul>
 * <li>建立新的 KeyStore 檔案</li>
 * <li>變更 KeyStore 檔案密碼</li>
 * <li>查詢所有 KeyStore 別名及其型態</li>
 * <li>儲存/讀取別名資料(以 SecretKeyEntry 方式)</li>
 * <li>取得 KeyStore 實例物件</li>
 * </ul>
 *
 *
 * 注意事項:
 * <ul>
 * <li>操作前請確認檔案路徑與密碼正確,避免資料遺失。</li>
 * <li>密碼變更時,會同步更新所有 KeyEntry 的密碼。</li>
 * <li>儲存資料時,會以 PBE(Password-Based Encryption)方式產生 SecretKeyEntry。</li>
 * <li>本工具類依賴 BaseSystemConstants 及 StringUtils,請確保相關常數與工具類已正確引入。</li>
 * </ul>
 *
 *
 * @author Lewis
 * @version 1.0
 */
public class KeyStoreUtils {
    /** Private constructor to prevent instantiation */
    private KeyStoreUtils() {
        throw new IllegalStateException("This is a utility class and cannot be instantiated");
    }

    /** default keystore type */
    public static final String TYPE_JKS = "JCEKS";

    /**
     * Check Key Store File is Exist or not
     * 
     * @param keyStoreFile     key store file name
     * @param keyStorePassword key store password
     * @return
     */
    private static boolean isKeyStoreFileExist(File keyStoreFile, String keyStorePassword) {
        return null != keyStoreFile && keyStoreFile.exists() && null != keyStorePassword;
    }

    /**
     * Change Key Store File Password
     *
     * @param keyStoreFileName    key store file name
     * @param oldKeyStorePassword Old key store password
     * @param newKeyStorePassword New key store password
     * @throws java.lang.Exception if any.
     */
    public static void changeKeyStorePassword(String keyStoreFileName, String oldKeyStorePassword,
            String newKeyStorePassword) throws Exception {
        if (StringUtils.isBlank(keyStoreFileName)) {
            keyStoreFileName = GlobalConstants.KEY_STORE_FILE;
        }
        if (StringUtils.isBlank(newKeyStorePassword)) {
            newKeyStorePassword = GlobalConstants.KEY_STORE_PASSWORD;
        }

        // Load the keystore
        KeyStore keyStore = KeyStore.getInstance(TYPE_JKS); // Or "PKCS12" depending on your keystore type
        FileInputStream fileInputStream = new FileInputStream(keyStoreFileName);
        keyStore.load(fileInputStream, oldKeyStorePassword.toCharArray());
        fileInputStream.close();

        // Iterate through aliases and update key entry passwords if they are different
        // This is crucial if your key entries have passwords independent of the
        // keystore password
        for (String alias : java.util.Collections.list(keyStore.aliases())) {
            if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
                // Assuming key entry password is the same as the old keystore password
                // If not, you'd need the old key password for each alias
                KeyStore.ProtectionParameter oldKeyProtection = new KeyStore.PasswordProtection(
                        oldKeyStorePassword.toCharArray());
                KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                        oldKeyProtection);

                // Create a new protection parameter for the key entry with the new password
                KeyStore.ProtectionParameter newKeyProtection = new KeyStore.PasswordProtection(
                        newKeyStorePassword.toCharArray());
                keyStore.setEntry(alias, privateKeyEntry, newKeyProtection);
            }
            if (keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
                KeyStore.ProtectionParameter oldKeyProtection = new KeyStore.PasswordProtection(
                        oldKeyStorePassword.toCharArray());
                KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias,
                        oldKeyProtection);
                // Create a new protection parameter for the key entry with the new password
                KeyStore.ProtectionParameter newKeyProtection = new KeyStore.PasswordProtection(
                        newKeyStorePassword.toCharArray());
                keyStore.setEntry(alias, secretKeyEntry, newKeyProtection);

            }
            if (keyStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {

                KeyStore.ProtectionParameter oldKeyProtection = new KeyStore.PasswordProtection(
                        oldKeyStorePassword.toCharArray());
                KeyStore.TrustedCertificateEntry trustedCertificateEntry = (KeyStore.TrustedCertificateEntry) keyStore
                        .getEntry(alias,
                                oldKeyProtection);
                // Create a new protection parameter for the key entry with the new password
                KeyStore.ProtectionParameter newKeyProtection = new KeyStore.PasswordProtection(
                        newKeyStorePassword.toCharArray());
                keyStore.setEntry(alias, trustedCertificateEntry, newKeyProtection);
            }
        }

        // Store the keystore with the new password
        try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileName)) {
            keyStore.store(fileOutputStream, newKeyStorePassword.toCharArray());
            System.out.println("Keystore password changed successfully!");
        } catch (Exception e) {
            throw new Exception("Error changing keystore password: " + e.getMessage());
        }

    }

    /**
     * List All Key Store Alias
     *
     * @param keyStoreFileName key store file name
     * @param keyStorePassword Old key store password
     * @return Map String, String alias and type
     * @throws java.lang.Exception if any.
     */
    public static Map<String, String> listAllKeyStoreAlias(String keyStoreFileName, String keyStorePassword)
            throws Exception {
        Map<String, String> mapAlias = new HashMap<>();
        if (StringUtils.isBlank(keyStoreFileName)) {
            keyStoreFileName = GlobalConstants.KEY_STORE_FILE;
        }
        if (StringUtils.isBlank(keyStorePassword)) { 
            keyStorePassword = GlobalConstants.KEY_STORE_PASSWORD;
        }
        KeyStore keyStore = KeyStore.getInstance(TYPE_JKS); // Or "PKCS12" depending on your keystore type
        try (FileInputStream fileInputStream = new FileInputStream(keyStoreFileName)) {
            // Load the keystore
            keyStore.load(fileInputStream, keyStorePassword.toCharArray());
            // keyStore.aliases()) 全部會轉回小寫
            for (String alias : java.util.Collections.list(keyStore.aliases())) {
                if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
                    mapAlias.put(alias, "PrivateKeyEntry");
                }
                if (keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
                    mapAlias.put(alias, "SecretKeyEntry");
                }
                if (keyStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {
                    mapAlias.put(alias, "TrustedCertificateEntry");
                }
            }
        } catch (Exception e) {
            throw new Exception("Error get keystore Alias List : " + e.getMessage());
        }
        return mapAlias;
    }

    /**
     * Create New Keystore File with file name and keyStorePassword.
     *
     * @param keyStoreFileName keyStore File Name
     * @param keyStorePassword keyStore Password
     * @throws java.lang.Exception exception
     */
    public static void createNewKeyStoreFile(String keyStoreFileName, String keyStorePassword) throws Exception {
        // if (StringUtils.isBlank(TYPE_JKS)) {
        // TYPE_JKS = KeyStore.getDefaultType();
        // }
        KeyStore keyStore = KeyStore.getInstance(TYPE_JKS);
        char[] passwordChar = keyStorePassword.toCharArray();
        keyStore.load(null, passwordChar);

        // Store away the keystore.
        FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileName);
        keyStore.store(fileOutputStream, passwordChar);
        fileOutputStream.close();
    }

    /**
     * Create New Keystore File with file name and Default keyStorePassword.
     *
     * @param keyStoreFileName keyStore File Name
     * @throws java.lang.Exception exception
     */
    public static void createNewKeyStoreWithDefaultPassword(String keyStoreFileName) throws Exception {
        createNewKeyStoreFile(keyStoreFileName, GlobalConstants.KEY_STORE_PASSWORD);
    }

    /**
     * Create New Keystore File with Default KeyStore file and keyStorePassword.
     *
     * @param keyStorePassword keyStore Password
     * @throws java.lang.Exception exception
     */
    public static void createDefaultKeyStoreWithPassword(String keyStorePassword) throws Exception {
        createNewKeyStoreFile(GlobalConstants.KEY_STORE_FILE, keyStorePassword);
    }

    /**
     * Create New Keystore File with Default keystore file and default password.
     *
     * @throws java.lang.Exception exception
     */
    public static void createNewKeyStoreWithDefault() throws Exception {
        String keyStorePassword = GlobalConstants.KEY_STORE_PASSWORD;
        createNewKeyStoreFile(GlobalConstants.KEY_STORE_FILE, keyStorePassword);
    }

    /**
     * Get Keystore from keystore file and Keystore Password
     *
     * @param keyStoreFileName keystore file
     * @param keyStorePassword a  String  object
     * @return KeyStore KeyStore Object
     * @throws java.lang.Exception exception
     */
    public static KeyStore getKeyStoreFile(String keyStoreFileName, String keyStorePassword) throws Exception {
        File keyStoreFile = new File(keyStoreFileName);
        if (!isKeyStoreFileExist(keyStoreFile, keyStorePassword)) {
            createNewKeyStoreFile(keyStoreFileName, keyStorePassword);
        }

        try (FileInputStream fileInputStream = new FileInputStream(keyStoreFile)) {
            KeyStore keyStore = KeyStore.getInstance(TYPE_JKS);
            keyStore.load(fileInputStream, keyStorePassword.toCharArray());
            return keyStore;
        } catch (Exception ex) {
            throw new Exception();
        }

    }

    /**
     * Get Keystore from keystore file and Default Password
     *
     * @return KeyStoreFile KeyStore file Name
     * @throws java.lang.Exception exception
     * @param KeyStoreFile a  String  object
     */
    public static KeyStore getKeyStoreFile(String KeyStoreFile) throws Exception {
        return getKeyStoreFile(KeyStoreFile, GlobalConstants.KEY_STORE_PASSWORD);
    }

    /**
     * Get Keystore from Default keystore and Keystore Password
     *
     * @param keyStorePassword Keystore Password
     * @return KeyStore KeyStore Object
     * @throws java.lang.Exception exception
     */
    public static KeyStore getKeyStore(String keyStorePassword) throws Exception {
        return getKeyStoreFile(GlobalConstants.KEY_STORE_FILE, keyStorePassword);
    }

    /**
     * Get Keystore from Default keystore and Default Password
     *
     * @return KeyStore KeyStore Object
     * @throws java.lang.Exception exception
     */
    public static KeyStore getKeyStore() throws Exception {
        return getKeyStoreFile(GlobalConstants.KEY_STORE_FILE, GlobalConstants.KEY_STORE_PASSWORD);
    }

    /**
     *
     * set Alias Data To KeyStore with KeyStore Password.
     *
     *
     * @param keyStoreFileName a  String  object
     * @param keyStorePassword a  String  object
     * @param alias            a  String  object
     * @param aliasData        a  String  object
     * @throws java.lang.Exception if any.
     */

    public static void setAliasDataToKeyStore(String keyStoreFileName, String keyStorePassword, String alias,
            String aliasData) throws Exception {

        // SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        // SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(
        // aliasData.toCharArray()));

        KeyStore keyStore = getKeyStoreFile(keyStoreFileName, keyStorePassword);
        KeyStore.Entry entry = keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(keyStorePassword.toCharArray()));
        if (null != entry) {
            // 刪除已存在的 alias
            keyStore.deleteEntry(alias);
        }

        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(aliasData.toCharArray()));
        keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP);

        FileOutputStream fileOutputStream = new java.io.FileOutputStream(keyStoreFileName);
        keyStore.store(fileOutputStream, keyStorePassword.toCharArray());
    }

    /**
     *
     * set Alias Data To Default KeyStore with KeyStore Password.
     *
     *
     * @param keyStorePassword a  String  object
     * @param alias            a  String  object
     * @param aliasData        a  String  object
     * @throws java.lang.Exception if any.
     */
    public static void setAliasDataToDefaultKeyStore(String keyStorePassword, String alias, String aliasData)
            throws Exception {
        setAliasDataToKeyStore(GlobalConstants.KEY_STORE_FILE, keyStorePassword, alias, aliasData);
    }

    /**
     *
     * set Alias Data To Default KeyStore with default keyStore Password.
     *
     *
     * @param alias     a  String  object
     * @param aliasData a  String  object
     * @throws java.lang.Exception if any.
     */
    public static void setAliasDataToDefaultKeyStore(String alias, String aliasData) throws Exception {
        setAliasDataToDefaultKeyStore(GlobalConstants.KEY_STORE_PASSWORD, alias, aliasData);
    }

    /**
     *
     * get Alias Data from KeyStore with keyStore Password.
     *
     *
     * @param keyStoreFileName a  String  object
     * @param keyStorePassword a  String  object
     * @param alias            a  String  object
     * @return a  String  object
     * @throws java.lang.Exception if any.
     */
    public static String getAliasDataFromKeystore(String keyStoreFileName, String keyStorePassword, String alias)
            throws Exception {

        KeyStore keyStore = KeyStore.getInstance(TYPE_JKS);
        keyStore.load(null, keyStorePassword.toCharArray());
        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        FileInputStream fIn = new FileInputStream(keyStoreFileName);

        keyStore.load(fIn, keyStorePassword.toCharArray());

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");

        KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias, keyStorePP);

        PBEKeySpec keySpec = (PBEKeySpec) factory.getKeySpec(
                ske.getSecretKey(),
                PBEKeySpec.class);

        char[] password = keySpec.getPassword();

        return new String(password);

    }

    /**
     *
     * get Alias Data from Default KeyStore with keyStore Password.
     *
     *
     * @param keyStorePassword a  String  object
     * @param alias            a  String  object
     * @return a  String  object
     * @throws java.lang.Exception if any.
     */
    public static String getAliasDataFromKeystore(String keyStorePassword, String alias)
            throws Exception {
        return getAliasDataFromKeystore(GlobalConstants.KEY_STORE_FILE, keyStorePassword, alias);
    }

    /**
     *
     * get Alias Data from Default KeyStore with Default keyStore Password
     *
     *
     * @param alias a  String  object
     * @return a  String  object
     * @throws java.lang.Exception if any.
     */
    public static String getAliasDataFromKeystore(String alias)
            throws Exception {
        String keyStorePassword = GlobalConstants.KEY_STORE_PASSWORD;
        return getAliasDataFromKeystore(keyStorePassword, alias);
    }
}

單元測試程式碼 KeyStoreUtilsTest.java

package tw.lewishome.webapp.base.utility.common;

import static org.junit.jupiter.api.Assertions.*;

import java.io.File;

import java.nio.file.Path;
import java.security.KeyStore;
import java.util.Map;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import tw.lewishome.webapp.GlobalConstants;

/**
 * Unit tests for KeyStoreUtils
 */
class KeyStoreUtilsTest {

    // (1) OS Command to change keystore password
    // $ keytool -storepasswd -keystore keystorename
    // Enter keystore password: <old password>
    // New keystore password: <new password>
    // Re-enter new keystore password: <new password>

    // (2) OS Command to change alias password
    // $ keytool -keypasswd -keystore keystorename -alias aliasname
    // Enter keystore password:
    // New key password for <aliasname>:
    // Re-enter new key password for <aliasname>:

    @TempDir
    Path tempDir;

    private String ksPath;

    @BeforeEach
    void setUp() {
        ksPath = tempDir.resolve("testkeystore.jceks").toString();
        // Ensure deleted before each test
        //
    }

    @AfterEach
    void tearDown() {
        FileUtils.deleteFile(ksPath);
    }
    /**
     * @throws Exception
     */
    @Test
    void testCreateNewKeyStoreFileAndExistence() throws Exception {

        KeyStoreUtils.createNewKeyStoreFile(ksPath, "keystorePass123");
        assertTrue(new File(ksPath).exists());
    }

    /**
     * @throws Exception
     */
    @Test
    void testSetAndGetAliasDataToKeyStore() throws Exception {
        KeyStoreUtils.createNewKeyStoreFile(ksPath, "keystorePass123");
        KeyStoreUtils.setAliasDataToKeyStore(ksPath, "keystorePass123", "testAlias", "testData");   

        String data = KeyStoreUtils.getAliasDataFromKeystore(ksPath, "keystorePass123", "testAlias");
        assertEquals("testData" , data);
    }

    /**
     * @throws Exception
     */
    @Test
    void testSetMultipleAliasesAndListAllKeyStoreAlias() throws Exception {
         KeyStoreUtils.createNewKeyStoreFile(ksPath, "keystorePass123");
        KeyStoreUtils.setAliasDataToKeyStore(ksPath, "keystorePass123", "testAlias", "testData");   

        KeyStoreUtils.setAliasDataToKeyStore(ksPath, "keystorePass123", "testAlias2", "testData2");

        Map<String, String> aliases = KeyStoreUtils.listAllKeyStoreAlias(ksPath, "keystorePass123");
        assertTrue(aliases.containsKey("testAlias".toLowerCase()));
        assertTrue(aliases.containsKey("testAlias2".toLowerCase()));
        assertEquals("SecretKeyEntry", aliases.get("testAlias".toLowerCase()));
        assertEquals("SecretKeyEntry", aliases.get("testAlias2".toLowerCase()));
    }

    

    /**
     * @throws Exception
     */
    @Test
    void testGetKeyStoreFileCreatesIfNotExist() throws Exception {

        KeyStore ks = KeyStoreUtils.getKeyStoreFile(ksPath, "keystorePass123");        
        assertNotNull(ks);
        assertTrue(new File(ksPath).exists());
    }

    /**
     * @throws Exception
     */
    @Test
    void testDefaultKeyStoreMethodsWithMockedConstants() throws Exception {

        KeyStoreUtils.createNewKeyStoreWithDefault();
        assertTrue(new File(GlobalConstants.KEY_STORE_FILE).exists());

        KeyStoreUtils.setAliasDataToDefaultKeyStore("testAlias", "testData");
        String data = KeyStoreUtils.getAliasDataFromKeystore("testAlias");
        assertEquals("testData", data);

        KeyStore ks = KeyStoreUtils.getKeyStore();
        assertNotNull(ks);
    }

    /**
     * @throws Exception
     */
    @Test
    void testSetAliasDataToKeyStoreWithDefaultPassword() throws Exception {

        KeyStoreUtils.createNewKeyStoreWithDefault();
        KeyStoreUtils.setAliasDataToDefaultKeyStore("testAlias", "testData");

        String data = KeyStoreUtils.getAliasDataFromKeystore("testAlias");
        assertEquals("testData", data);

    }

    @Test
    void testCreateAndGetKeyStore() throws Exception {
        String password = "oldPass123";
        // create keystore
        KeyStoreUtils.createNewKeyStoreFile(ksPath, password);
        assertTrue(FileUtils.checkFileExist(ksPath));

        KeyStore ks = KeyStoreUtils.getKeyStoreFile(ksPath, password);
        assertNotNull(ks);
    }

    @Test
    void testSetAndGetAliasDataAndList() throws Exception {
        String password = "aliasPass123";
        String alias = "alias1";
        String aliasData = "secretData123";

        KeyStoreUtils.createNewKeyStoreFile(ksPath, password);

        // set alias data
        KeyStoreUtils.setAliasDataToKeyStore(ksPath, password, alias, aliasData);

        // get alias data
        String got = KeyStoreUtils.getAliasDataFromKeystore(ksPath, password, alias);
        assertEquals(aliasData, got);

        // list aliases
        Map<String, String> aliases = KeyStoreUtils.listAllKeyStoreAlias(ksPath, password);
        assertNotNull(aliases);
        assertTrue(aliases.containsKey(alias));
        assertEquals("SecretKeyEntry", aliases.get(alias));
    }

    @Test
    void testChangeKeyStorePassword() throws Exception {
        String oldPass = "oldKeystorePwd";
        String newPass = "newKeystorePwd";
        String alias = "aliasChange";
        String aliasData = "changeSecret";

        // create and add alias
        KeyStoreUtils.createNewKeyStoreFile(ksPath, oldPass);
        KeyStoreUtils.setAliasDataToKeyStore(ksPath, oldPass, alias, aliasData);

        // change keystore password
        KeyStoreUtils.changeKeyStorePassword(ksPath, oldPass, newPass);

        // After change, loading with old password should fail
        assertThrows(Exception.class, () -> KeyStoreUtils.getKeyStoreFile(ksPath, oldPass));

        // But with new password we should still retrieve the alias data
        String got = KeyStoreUtils.getAliasDataFromKeystore(ksPath, newPass, alias);
        assertEquals(aliasData, got);
    }

    /**
     * @throws Exception
     */
    @Test
    void testChangeKeyStorePassword2() throws Exception {
        KeyStoreUtils.createNewKeyStoreFile(ksPath, "keystorePass123");
        KeyStoreUtils.setAliasDataToKeyStore(ksPath, "keystorePass123", "testAlias", "testData");

        String newPassword = "newPassword456";
        KeyStoreUtils.changeKeyStorePassword(ksPath, "keystorePass123", newPassword);

        // Should be able to get alias data with new password
        String data = KeyStoreUtils.getAliasDataFromKeystore(ksPath, newPassword, "testAlias");
        assertEquals("testData", data);

        // Should fail with old password
        assertThrows(Exception.class, () -> {
            KeyStoreUtils.getAliasDataFromKeystore(ksPath, "keystorePass123", "testAlias");
        });
    }
}


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言