· 6 years ago · Oct 13, 2019, 09:38 PM
1package sample.logic;
2
3import javax.crypto.KeyGenerator;
4import javax.crypto.SecretKey;
5import java.io.FileInputStream;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.security.KeyStore;
9import java.security.KeyStoreException;
10import java.security.NoSuchAlgorithmException;
11import java.security.UnrecoverableKeyException;
12import java.security.cert.CertificateException;
13
14class KeyLoader {
15
16 private static final String KEYSTORE_TYPE = "JCEKS";
17 private static final String KEYSTORE_NAME = "KeyStore";
18 private static final String SECRET_KEY_NAME = "secretKeyAlias";
19 private static final String KEYSTORE_PWD = "password";
20
21 static SecretKey getKey(String algorithm) throws SecretKeyException{
22
23 SecretKey key = loadKey();
24
25 if (key == null){
26 try {
27 key = KeyGenerator.getInstance(algorithm).generateKey();
28 } catch (NoSuchAlgorithmException e) {
29 throw new SecretKeyException();
30 }
31 try {
32 storeKey(key);
33 } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
34 throw new SecretKeyException();
35 }
36 }
37
38 return key;
39 }
40
41 private static void storeKey(SecretKey secretKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
42
43 KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
44 ks.load(null, KEYSTORE_PWD.toCharArray());
45
46 KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
47 KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(secretKey);
48 ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
49 try (FileOutputStream fos = new FileOutputStream(KEYSTORE_NAME)) {
50 ks.store(fos, KEYSTORE_PWD.toCharArray());
51 } catch (Exception asd) {
52 System.out.println(asd.getMessage());
53 }
54 }
55
56 private static SecretKey loadKey() {
57 KeyStore ks = null;
58 try {
59 ks = KeyStore.getInstance(KEYSTORE_TYPE);
60 ks.load(new FileInputStream(KEYSTORE_NAME), KEYSTORE_PWD.toCharArray());
61 }
62
63 catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
64 System.out.println(e.getMessage());
65 return null;
66 }
67 try {
68 return (SecretKey) ks.getKey(SECRET_KEY_NAME, KEYSTORE_PWD.toCharArray());
69 } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
70 System.out.println(e.getMessage());
71 return null;
72 }
73 }
74
75
76}