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
    评论
首先,您需要生成RSA公钥私钥。可以使用Java中的`KeyPairGenerator`类来生成公钥私钥。以下是一个示例代码: ```java import java.security.*; public class RSAKeyGenerator { public static void main(String[] args) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); System.out.println("Private Key: " + privateKey); System.out.println("Public Key: " + publicKey); } } ``` 生成的公钥私钥将打印在控制台上。 接下来,您需要将公钥私钥保存到文件中。可以使用Java中的`KeyStore`类来保存公钥私钥。以下是一个示例代码: ```java import java.io.FileOutputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; public class RSAKeyStore { public static void main(String[] args) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("mykey", privateKey, "mypass".toCharArray(), new Certificate[] { }); keyStore.setCertificateEntry("mycert", new TestCertificate(publicKey)); FileOutputStream fos = new FileOutputStream("mykeystore.jks"); keyStore.store(fos, "mystorepass".toCharArray()); fos.close(); } } class TestCertificate extends Certificate { private PublicKey publicKey; public TestCertificate(PublicKey publicKey) { super("X.509"); this.publicKey = publicKey; } @Override public PublicKey getPublicKey() { return publicKey; } @Override public byte[] getEncoded() { return new byte[0]; } @Override public void verify(PublicKey key) { } @Override public void verify(PublicKey key, String sigProvider) { } @Override public String toString() { return "TestCertificate"; } } ``` 这个示例代码将生成一个Java密钥库,并将私钥公钥保存为键值对。然后将密钥库保存到文件中。 现在,您可以使用公钥加密文件,然后使用私钥解密文件。以下是示例代码: ```java import javax.crypto.Cipher; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.*; public class RSAEncryption { public static void main(String[] args) throws Exception { // 读取密钥库文件 String keyStoreFile = "mykeystore.jks"; String keyStorePass = "mystorepass"; String keyAlias = "mykey"; String keyPass = "mypass"; KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStoreFile), keyStorePass.toCharArray()); // 获取私钥 PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPass.toCharArray()); // 加密文件 String inputFile = "plaintext.txt"; String encryptedFile = "encrypted.txt"; Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyStore.getCertificate("mycert").getPublicKey()); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(encryptedFile); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { byte[] encrypted = cipher.update(buffer, 0, len); if (encrypted != null) { fos.write(encrypted); } } byte[] encrypted = cipher.doFinal(); if (encrypted != null) { fos.write(encrypted); } fis.close(); fos.flush(); fos.close(); // 解密文件 String decryptedFile = "decrypted.txt"; cipher.init(Cipher.DECRYPT_MODE, privateKey); fis = new FileInputStream(encryptedFile); fos = new FileOutputStream(decryptedFile); buffer = new byte[1024]; while ((len = fis.read(buffer)) != -1) { byte[] decrypted = cipher.update(buffer, 0, len); if (decrypted != null) { fos.write(decrypted); } } byte[] decrypted = cipher.doFinal(); if (decrypted != null) { fos.write(decrypted); } fis.close(); fos.flush(); fos.close(); } } ``` 这个示例代码将使用公钥加密`plaintext.txt`文件,并将加密后的文件保存为`encrypted.txt`。然后,使用私钥解密`encrypted.txt`文件,并将解密后的文件保存为`decrypted.txt`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

晒干的老咸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值