JAVA加载keystore文件,获取公钥和私钥

总结java如何加载keystore文件,获取公私钥信息

    /**
     * Java密钥库(Java Key Store,JKS)KEY_STORE
     */
    private static final String KEY_STORE = "JKS";

    private static final String X509 = "X.509";

    /**
     * 从公钥文件当中读取公钥,公钥文件存储在设备某个特定位置
     * 
     * @param publicKeyFilePath 公钥文件存放路径
     * @return
     */
    public static String loadPublicKey(String publicKeyFilePath) throws Exception {
        String publicKey = "";
        File file = new File(publicKeyFilePath);
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            publicKey = reader.readLine();
            // System.out.println("publicKey: " + publicKey);
            reader.close();
        } else {
            throw new RuntimeException("PublicKey File not exist!");
        }
        return publicKey;
    }

    /**
     * 从私钥文件当中读取私钥,私钥文件存储在我们自己的签名工具当中
     * 
     * @param privateFilePath 私钥文件存储路径
     * @return
     */
    public static String loadPrivateKey(String privateFilePath) throws Exception {
        String privateKey = "";
        File file = new File(privateFilePath);
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            privateKey = reader.readLine();
            // System.out.println("privateKey: " + privateKey);
            reader.close();
        } else {
            throw new RuntimeException("PublicKey File not exist!");
        }
        return privateKey;
    }

    /**
     * 获得KeyStore
     * 
     * @param keyStorePath
     * @param password
     */
    private static KeyStore getKeyStore(String keyStorePath, String password)
            throws Exception {

        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance(KEY_STORE);
        ks.load(is, password.toCharArray());
        is.close();
        return ks;
    }

    /**
     * 由KeyStore获得私钥
     * 
     * @param keyStorePath
     * @param alias
     * @param storePass
     */
    private static PrivateKey getPrivateKey(String keyStorePath, String alias, String storePass,
            String keyPass) throws Exception {
        KeyStore ks = getKeyStore(keyStorePath, storePass);
        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
        return key;
    }

    /**
     * 由Certificate获得公钥
     * 
     * @param keyStorePath KeyStore路径
     * @param alias 别名
     * @param storePass KeyStore访问密码
     */
    private static PublicKey getPublicKey(String keyStorePath, String alias, String storePass)
            throws Exception {
        KeyStore ks = getKeyStore(keyStorePath, storePass);
        PublicKey key = ks.getCertificate(alias).getPublicKey();
        return key;
    }

    /**
     * 从KeyStore中获取公钥,并经BASE64编码
     * @param keyStorePath
     * @param alias
     * @param storePass
     */
    public static String getStrPublicKey(String keyStorePath, String alias, String storePass)
            throws Exception {
        PublicKey key = getPublicKey(keyStorePath, alias, storePass);
        String strKey = Base64Utils.encode(key.getEncoded());
        return strKey;
    }

    /**
     * 获取经BASE64编码后的私钥
     * @param alias
     * @param storePass
     * @param keyPass
     */
    public static String getStrPrivateKey(String keyStorePath, String alias, String storePass,
            String keyPass) throws Exception {

        PrivateKey key = getPrivateKey(keyStorePath, alias, storePass, keyPass);
        String strKey = Base64Utils.encode(key.getEncoded());
        return strKey;
    }

    public static void main(String args[]) throws Exception {
        // KeyStoreTool.loadPrivateKey("privateKey.txt");
        // KeyStoreTool.loadPublicKey("publicKey.txt");

        String publicKey = KeyStoreTool.getStrPublicKey("appstore.keystore", "appstore", "123456");
        System.out.println("publicKey: " + publicKey);
        String privateKey = KeyStoreTool.getStrPrivateKey("appstore.keystore", "appstore",
                "123456", "123456");
        System.out.println("privateKey: " + privateKey);
    }

Base64Utils的内容如下(import org.apache.commons.codec.binary.Base64):

Base64来自apache包commons-codec-1.11.jar


    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    /**
     * BASE64字符串解码为二进制数据
     * 
     * @param base64
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decodeBase64(base64.getBytes());
    }

    /**
     * 二进制数据编码为BASE64字符串
     * @param bytes
     */
    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * 将文件编码为BASE64字符串
     * 大文件慎用,可能会导致内存溢出
     * @param filePath 文件绝对路径
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }

    /**
     * BASE64字符串转回文件
     * @param filePath 文件绝对路径
     * @param base64 编码字符串
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }

    /**
     * 文件转换为二进制数组
     * @param filePath 文件路径
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = new byte[0];
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
        }
        return data;
    }

    /**
     * 二进制数据写文件
     * @param bytes 二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }
 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晒干的老咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值