· 7 years ago · Aug 04, 2018, 01:52 AM
1package br.inf.cbds.javaseguro;
2
3import javax.crypto.Cipher;
4import javax.crypto.KeyGenerator;
5import javax.crypto.SecretKey;
6import javax.crypto.spec.SecretKeySpec;
7
8public class UtilJCE {
9
10 private KeyGenerator kgen;
11 private SecretKey secretKey;
12 private Cipher cipher;
13 private SecretKeySpec specKey;
14
15 public UtilJCE()
16 {
17 try
18 {
19 kgen = KeyGenerator.getInstance("Blowfish");
20 secretKey = kgen.generateKey();
21 byte[] bytes = secretKey.getEncoded();
22 specKey = new SecretKeySpec(bytes, "Blowfish");
23 cipher = Cipher.getInstance("Blowfish");
24 cipher.init(Cipher.ENCRYPT_MODE, specKey);
25 }
26 catch (Exception e)
27 {
28 System.out.println("Exception: " + e.getMessage());
29 }
30 }
31
32 public static void main(String[] args) {
33
34 String senha = "123mudar";
35
36 UtilJCE jce = new UtilJCE();
37 System.out.println("Senha original: " + senha);
38 System.out.println("Senha Criptografada: " + jce.criptografa(senha));
39 System.out.println("Senha Descriptografa: " + jce.descriptografa(senha));
40
41 }
42
43 public String criptografa(String senha)
44 {
45 try
46 {
47 byte[] encrypted = cipher.doFinal(senha.getBytes());
48 return new String(encrypted);
49 }
50 catch (Exception e)
51 {
52 System.out.println("Exception: " + e.getMessage());
53 }
54 return null;
55 }
56
57 public String descriptografa(String senha)
58 {
59 try
60 {
61 byte[] encrypted = cipher.doFinal(senha.getBytes());
62 cipher.init(Cipher.DECRYPT_MODE, specKey);
63 byte[] decrypted = cipher.doFinal(encrypted);
64 senha = new String(decrypted);
65 return senha;
66 }
67 catch (Exception e)
68 {
69 System.out.println("Exception: " + e.getMessage());
70 }
71 return null;
72 }
73}