· 6 years ago · Oct 03, 2019, 05:26 PM
1package actividad_2;
2import java.security.*;
3import javax.crypto.*;
4import java.util.*;
5
6public class Actividad_2 {
7
8 public static void main(String[] args) {
9
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Introduce la longitud de la clave: ");
12
13 int numero;
14 numero = sc.nextInt();
15 generateKey(numero);
16
17 sc.close();
18 }
19
20 protected static void generateKey (int numero) {
21
22 SecretKey llave = null;
23
24 try {
25 KeyGenerator k = KeyGenerator.getInstance("AES");
26 k.init(numero);
27 llave = k.generateKey();
28
29 System.out.println(llave);
30
31 //clave base64
32 String base64 = Base64.getEncoder().encodeToString(llave.getEncoded());
33
34 System.out.println("Base64 = " + base64);
35
36 //clave bytes
37 byte[] convByte = llave.getEncoded();
38 String convByte2 = "";
39
40 for (int i = 0; i < convByte.length; i++) {
41 convByte2 += convByte[i] + " ";
42 }
43 System.out.println("Byte = " + convByte2);
44
45 //clave bits
46 String convBits = "";
47 for (int i = 0; i < convByte.length; i++) {
48 convBits += Integer.toBinaryString(convByte[i]);
49 }
50 System.out.println("Bits = " + convBits);
51
52
53 } catch (NoSuchAlgorithmException e) {
54
55 e.printStackTrace();
56 }
57 }
58
59}