· 5 years ago · Apr 30, 2020, 11:30 AM
1import javax.crypto.*;
2import javax.crypto.spec.SecretKeySpec;
3import java.io.*;
4import java.security.*;
5import java.security.cert.CertificateException;
6
7public class CipherManager {
8
9 private SecretKey secretKey;
10
11 public CipherManager() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
12
13 //check if folder exist
14 File theDir = new File("stc_files");
15 if (!theDir.exists()) {
16 try{
17 theDir.mkdir();
18 }
19 catch(SecurityException e){
20 e.getMessage();
21 }
22 }
23
24 Boolean exists = true;
25 KeyStore keyStore = KeyStore.getInstance("JCEKS");
26 char[] password = "4##!!dkDDD44%%%%435$%3".toCharArray();
27 String path = "stc_files/keystore.stc";
28 File file = new File(path);
29
30 //try to load keystore file
31 try {
32 java.io.FileInputStream fis = new FileInputStream(path);
33 keyStore.load(fis, password);
34 KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);
35 KeyStore.SecretKeyEntry secretKeyEnt = (KeyStore.SecretKeyEntry)keyStore.getEntry("secretKeyAlias", protectionParam);
36 this.secretKey = secretKeyEnt.getSecretKey();
37
38 } catch (FileNotFoundException | UnrecoverableEntryException e) {
39 exists = false;
40 }
41
42 if (!exists) {
43 keyStore.load(null, password);
44 KeyGenerator keyGen = KeyGenerator.getInstance("DES");
45 SecureRandom secRandom = new SecureRandom();
46 keyGen.init(secRandom);
47 this.secretKey = keyGen.generateKey();
48 KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);
49 KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(this.secretKey);
50 keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);
51
52 //save keystore to file
53 FileOutputStream out = new FileOutputStream(file);
54 keyStore.store(out, password);
55 out.close();
56 }
57
58 }
59
60 public Cipher getEncryptCipher() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
61 Cipher cipher = Cipher.getInstance("DES");
62 cipher.init(cipher.ENCRYPT_MODE, this.secretKey);
63 return cipher;
64 }
65
66 public Cipher getDecryptCipher() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
67 Cipher cipher = Cipher.getInstance("DES");
68 cipher.init(cipher.DECRYPT_MODE, this.secretKey);
69 return cipher;
70 }
71
72}