如何使用JCE存储私钥

时间:2016-02-24 20:47:30

标签: java cryptography keystore private-key jce

我是JCA的新手,所以请原谅我所犯的任何简单错误。我试图熟悉Java加密套件。我正在努力将私钥放入我自己的KeyStore中。每当我将文件放入密钥库时,没有问题。编码是PKCS#8,应该是。然而,问题是当我去检索密钥时,它说这个密钥无法恢复,因为它没有放在PKCS#8格式下的密钥库中。她是我插入密钥的代码

    public static void saveToKeyStore(Key key, String password, String alias)
{
    try
    {
        KeyStore ks = KeyStore.getInstance("JCEKS");

        InputStream readStream = null;
        File tmpFile = new File(System.getProperty("user.home") + "/.etc/.keystore");

        if(tmpFile.exists())
        {
            System.out.println("file exists");
            readStream = new FileInputStream(System.getProperty("user.home") + "/.etc/.keystore");
            ks.load(readStream, password.toCharArray());
        }else
        {
            System.out.println("file doesn't exist");
            ks.load(null, password.toCharArray());

            tmpFile.getParentFile().mkdirs();

        }



        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());

        KeyFactory kf = KeyFactory.getInstance("RSA");

        PrivateKey tempKey = kf.generatePrivate(keySpec);

        System.out.println("encoding format: " + tempKey.getFormat());

        ks.setKeyEntry(alias, tempKey.getEncoded(), null);

        OutputStream writeStream = new FileOutputStream(System.getProperty("user.home") + "/.etc/.keystore");

        ks.store(writeStream, password.toCharArray());

        System.out.println("key was created: " + ks.isKeyEntry(alias));

        writeStream.close();

    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

这是我的代码来检索密钥

    public static Key retrieveFromKeyStore(String password, String alias)
{
    Key returnKey = null;
    PrivateKey privateKey = null;
    try
    {
        KeyStore ks = KeyStore.getInstance("JCEKS");

        InputStream readStream = new FileInputStream(System.getProperty("user.home") + "/.etc/.keystore");

        ks.load(readStream, password.toCharArray());


        System.out.println("is a key: " + alias + " \n well?: " + ks.isKeyEntry(alias));

        System.out.println("return key encoding format: " + ks.getKey(alias, password.toCharArray()));

        returnKey = ks.getKey(alias, password.toCharArray());

        KeyFactory kf = KeyFactory.getInstance("RSA");

        privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(returnKey.getEncoded()));

        if(privateKey != null)
        {
            System.out.println("privateKey: " + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        }else
        {
            System.out.println("return key was null");
        }

        readStream.close();

    }catch(Exception e)
    {
        e.printStackTrace();
    }
    return privateKey;
}

对此问题的任何帮助或对该主题的好材料的参考将不胜感激。

0 个答案:

没有答案