我需要创建一个空的KeyStore文件(名为KeyStoreAES.jks),然后将AES SecretKey存储到该文件中,所有这些都是通过Java编程实现的。
我具有创建.jks文件的功能:
//Función that creates KeyStoreAES.jks
private static void CreateKeyStoreAES(String path)
{
try
{
//Check if file already exists
File keyStoreFile = new File(path);
if (keyStoreFile.exists())
{
keyStoreFile.delete();
} //if
keyStoreFile.createNewFile();
}
catch (IOException ex)
{
System.out.println("IOException");
}
} //CrearKeyStoreAES
此功能工作正常。然后,我还有另一个功能可以将密钥插入该文件:
//Storing Key into KeyStore file
private static void StoreKey(String path, SecretKey key)
{
try
{
//KeyStore
KeyStore ks = KeyStore.getInstance("JKS"); //JCEKS, JKS
//FileInputStream
FileInputStream fis = new FileInputStream(path);
//Load KeyStore file
ks.load(fis, keyStorePass);
}
catch (CertificateException ex)
{
System.out.println("CertificateException");
}
catch (IOException ex)
{
System.out.println("IOException");
}
catch (KeyStoreException ex)
{
System.out.println("KeyStoreException");
}
catch (NoSuchAlgorithmException ex)
{
System.out.println("NoSuchAlgorithmException");
} //try
} //StoreKey
从KeyStore类调用加载函数将引发IOException。这是因为尝试加载的文件为空吗?据我在互联网上搜索过的,要将密钥插入KeyStore,您需要将该文件加载到KeyStore对象中。
是,JKS格式需要标题和尾部信息,因此,空文件不是有效的JKS,而没有条目的JKS也不是空文件。
要从头开始创建JKS,不要加载任何文件/数据:
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null); // NO INPUTSTREAM HERE
...
ks.setKeyEntry(...); // or .setEntry(...) as desired
...
OutputStream fo = Files.newOutputStream(Path.of("myfile")); // or similar
ks.store(fo,password); fo.close();
但是,JKS格式不支持SecretKey
条目,因此仍然无法解决您的问题。您将需要使用其他格式,例如JCEKS或PKCS12或BouncyCastle的BKS-所有这些格式也不能有效地成为空文件。