I am using SecretKeyFactory.getInstance("some String") to encrypt/dycrypt a string.But I am using SecretKeyFactory.getInstance("some String") as the key , but I need to use the String key from a file name and that file instance I need to pass inside the SecretKeyFactory.getInstance() method which I can't do.
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");// here i need to replace
SecretKeyFactory factory = SecretKeyFactory.getInstance(keyFis.toString());
char[] password = "Pass@word1".toCharArray();
byte[] salt = "S@1tS@1t".getBytes("UTF-8");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
return new SecretKeySpec(encoded, "AES");
I am doing
// reading the key
String fileName = "C://somewhere//aesKey.dat";
FileInputStream keyFis = new FileInputStream(fileName);
byte[] encKey = new byte[keyFis.available()];
keyFis.read(encKey);
keyFis.close();
SecretKeyFactory factory = SecretKeyFactory.getInstance(keyFis.toString());
char[] password = "Pass@word1".toCharArray();
byte[] salt = "S@1tS@1t".getBytes("UTF-8");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
return new SecretKeySpec(encoded, "AES");
But I am getting below exception
Exception in thread "main" java.security.NoSuchAlgorithmException: java.io.FileInputStream@5ea75ea7 SecretKeyFactory not available
at javax.crypto.SecretKeyFactory.<init>(Unknown Source)
at javax.crypto.SecretKeyFactory.getInstance(Unknown Source)
at test.Main.generateKey(Main.java:66)
at test.Main.getCipher(Main.java:42)
at test.Main.Encrypt(Main.java:30)
at test.Main.main(Main.java:21)
How to solve this
If C:\\\\somewhere\\\\aesKey.dat
contains the AES key, then you can read the file into a byte[]
and directly create a Key
from that, because a SecretKeySpec
implements the Key
interface.
String fileName = "C:\\somewhere\\aesKey.dat";
byte[] encoded = Files.readAllBytes(Paths.get(fileName));
return new SecretKeySpec(encoded, "AES");
Make sure that you import java.nio.file.*
.
Never use FileInputStream#available
to determine the size of the file. The returned size can be smaller than the actual file, because the reader is buffered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.