-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyManager.java
More file actions
38 lines (33 loc) · 1.27 KB
/
Copy pathKeyManager.java
File metadata and controls
38 lines (33 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class KeyManager {
public static SecretKey newKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
}
public static void saveKey(SecretKey key) throws IOException {
// encode key as byte array
byte[] encoded = key.getEncoded();
FileOutputStream os = new FileOutputStream("keys.txt");
// write key to file
os.write(encoded);
os.close();
}
public static SecretKey loadKey(String filepath) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException
{
File file = new File(filepath);
byte[] encoded = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(encoded);
dis.close();
return new SecretKeySpec(encoded, "AES");
}
public static void main(String[] args) throws Exception {
SecretKey key = newKey();
saveKey(key);
}
}