· 9 years ago · Oct 24, 2016, 03:40 PM
1package m9.uf1.e1.abeltorres;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
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;
13import javax.crypto.KeyGenerator;
14import javax.crypto.SecretKey;
15
16public class A06_GuardarClausKeystore {
17
18 public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
19 SecretKey sKey = atzar(); //La clau generada a l' atzar
20
21 guardarKeyStore(sKey); //Guarda aquesta clau generada a l' atzar a la KeyStore
22
23 //5. Mostri la clau (bytes) recuperada del fitxer per consola
24 SecretKey sKeyRecupera = recuperarKeyStore(); //Recuperem la clau de la KeyStore per mostrar-la després
25
26 String clau = byteArrayToString(sKeyRecupera.getEncoded());
27 System.out.println("La recuperada és: " + clau);
28 }
29
30 //1. Genera una clau simètrica a l' atzar
31
32 public static SecretKey atzar(){ //Genera una clau a l' atzar i la mostra
33 String algorisme = "", sfinal = "";
34 int keySize = 0;
35 SecretKey sKey = null;
36
37 algorisme = "AES";
38 keySize = 192;
39 sKey = keygenKeyGeneration(algorisme, keySize);
40 if( sKey == null ){
41 System.out.println(algorisme + " (" + keySize + "bits): " + "Algorisme o clau incorrecta");
42 }
43 else{
44 sfinal = byteArrayToString(sKey.getEncoded());
45 //2. Mostri la clau (bytes) per consola
46 System.out.println(algorisme + " (" + keySize + "bits): " + sfinal);
47 }
48
49 return sKey;
50 }
51
52 //3. Guardi la clau a un keystore de tipus JCEKS
53
54 public static void guardarKeyStore(SecretKey sKey) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException{
55 SecretKey secretKey = sKey; // clau simètrica que es guarda
56 String fileName = "contrasenya.key"; //fitxer on es guarda el keystore
57 String filePassword = "123456"; //contrasenya per accedir al keystore
58 String alias = "c1"; // nom identificador de la clau
59 String keyPassword = "123456"; // contrasenya per accedir a la clau
60 File file = new File(fileName);
61
62 // Es crea un keystore de tipus JCEKS
63 KeyStore keyStore = KeyStore.getInstance("JCEKS");
64
65 // Si el keystore existex, es recupera el que hi ha, si no se'n crea un de temporal
66 if (file.exists()) {
67 keyStore.load(new FileInputStream(file), filePassword.toCharArray());
68 }
69 else {
70 keyStore.load(null, null);
71 }
72 // Guardar la clau com una nova Entry del KeyStore
73 keyStore.setKeyEntry(alias, secretKey, keyPassword.toCharArray(), null);
74
75 // Guardar el keyStore al fitxer
76 keyStore.store(new FileOutputStream(file), filePassword.toCharArray());
77 }
78
79 //4. Recuperi la clau del keystore mitjançant l'alies
80
81 public static SecretKey recuperarKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException{
82 String fileName = "contrasenya.key"; //fitxer on es guarda el keystore
83 String filePassword = "123456"; //contrasenya per accedir al keystore
84 String alias = "c1"; // nom identificador de la clau
85 String keyPassword = "123456";// contrasenya per accedir a la clau
86
87 KeyStore ks = KeyStore.getInstance("JCEKS");
88
89 ks.load(new FileInputStream(fileName), filePassword.toCharArray());
90
91 SecretKey key = (SecretKey) ks.getKey(alias, keyPassword.toCharArray());
92
93 return key;
94 }
95
96 public static SecretKey keygenKeyGeneration(String algorisme, int keySize) { //Genera clau a l' atzar segons l' algorisme entrat per parà mentre i la mida de la clau
97 SecretKey sKey = null;
98 if (((keySize == 128)||(keySize == 192)||(keySize == 256)) && algorisme == "AES" ) {
99 try {
100 KeyGenerator kgen = KeyGenerator.getInstance(algorisme);
101 kgen.init(keySize);
102 sKey = kgen.generateKey();
103 }
104 catch (NoSuchAlgorithmException ex) {
105 System.err.println("Generador no disponible.");
106 }
107 }
108 else if(keySize == 168 && algorisme == "DESede"){
109 try {
110 KeyGenerator kgen = KeyGenerator.getInstance(algorisme);
111 kgen.init(keySize);
112 sKey = kgen.generateKey();
113 }
114 catch (NoSuchAlgorithmException ex) {
115 System.err.println("Generador no disponible.");
116 }
117 }
118 else if(keySize == 56 && algorisme == "DES"){
119 try {
120 KeyGenerator kgen = KeyGenerator.getInstance(algorisme);
121 kgen.init(keySize);
122 sKey = kgen.generateKey();
123 }
124 catch (NoSuchAlgorithmException ex) {
125 System.err.println("Generador no disponible.");
126 }
127 }
128 return sKey; //Retorna la clau generada o null
129 }
130
131 private static String byteArrayToString(byte[] transform) { //Retorna l' array de bytes en string
132 StringBuffer hexString = new StringBuffer();
133 for (int i=0;i<transform.length;i++) {
134 hexString.append(Integer.toHexString(0xFF & transform[i]));
135 }
136 return hexString.toString();
137 }
138}