我目前正在学习Java中的加密/解密技术,我遇到的一个主要问题是将密钥存储在.jks文件中,并能够在不同的启动过程中加载它。在我的调用类中,它调用构造函数,这是它的代码:
public Encrypt_Decrypt() throws NoSuchAlgorithmException, NoSuchPaddingException
{
Cipher cipher = Cipher.getInstance("AES");
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
ivSpec = ivParams;
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
byte[] keyBytes = secretKey.getEncoded();
SecretKeySpec sks = new SecretKeySpec(keyBytes, "AES");
key = sks;
KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(key);
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection("password".toCharArray());
try
{
File f = new File("keystore.jks");
KeyStore keyStore = KeyStore.getInstance("JKS");
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream("keystore");
}
finally
{
if (fis != null)
{
fis.close();
}
}
keyStore.load(fis, "password".toCharArray());
keyStore.setEntry("key", entry, protParam);
try (FileOutputStream fout = new FileOutputStream(f))
{
keyStore.store(fout, "password".toCharArray());
;
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
在调用类中启动此代码后,这是它返回的错误:
keystore (The system cannot find the file specified)
在我的代码中我创建了文件,为什么它有问题?我查看了我的项目文件夹,并没有保存在那里,所以我必须做些什么才能创建,存储和使用这个文件而没有问题?
答案 0 :(得分:2)
keystore (The system cannot find the file specified)
消息与此行有关:
new java.io.FileInputStream("keystore");
看起来应该使用File f
?类似于下面处理FileOutputStream
的方法效果很好:
try (FileInputStream fis = new FileInputStream(f)) {
keyStore.load(fis, "password".toCharArray());
}
作为参考,还有另一个错误在那里等待。尝试将AES对称密钥存储在JKS密钥库中会导致此错误:
java.security.KeyStoreException: Cannot store non-PrivateKeys
at sun.security.provider.JavaKeyStore.engineSetKeyEntry(JavaKeyStore.java:258)
at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(JavaKeyStore.java:56)
at java.security.KeyStoreSpi.engineSetEntry(KeyStoreSpi.java:550)
at sun.security.provider.KeyStoreDelegator.engineSetEntry(KeyStoreDelegator.java:179)
at sun.security.provider.JavaKeyStore$DualFormatJKS.engineSetEntry(JavaKeyStore.java:70)
at java.security.KeyStore.setEntry(KeyStore.java:1557)
at KeystoreTest.main(KeystoreTest.java:44)
这是因为JKS商店类型仅支持公钥/私钥 - also here。
使用新的JCEKS密钥库,您的示例代码可以正常工作:
File f = new File("keystore.jceks");
KeyStore keyStore = KeyStore.getInstance("JCEKS");