· 9 years ago · Aug 28, 2016, 12:02 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package br.com.solutionsource.forcavendas.seguranca;
7
8import java.security.spec.KeySpec;
9import javax.crypto.Cipher;
10import javax.crypto.SecretKey;
11import javax.crypto.SecretKeyFactory;
12import javax.crypto.spec.DESedeKeySpec;
13import org.apache.commons.codec.binary.Base64;
14
15/**
16 *
17 * @author Marcelo
18 */
19public class Criptografia {
20
21 private static final String UNICODE_FORMAT = "UTF8";
22 private KeySpec ks;
23 private SecretKeyFactory skf;
24 private Cipher cipher;
25 byte[] arrayBytes;
26 private String myEncryptionScheme;
27 private String chave; // 2 x 12 caracteres
28 SecretKey key;
29
30 public Criptografia() throws Exception {
31
32 chave = "AChaveSeguraAChaveSegura"; // 2 x 12 caracteres
33 myEncryptionScheme = "DESede";
34 arrayBytes = chave.getBytes(UNICODE_FORMAT);
35 ks = new DESedeKeySpec(arrayBytes);
36 skf = SecretKeyFactory.getInstance(myEncryptionScheme);
37 cipher = Cipher.getInstance(myEncryptionScheme);
38 key = skf.generateSecret(ks);
39 }
40
41 public String criptografa(String texto) {
42 String criptografado = null;
43 try {
44 cipher.init(Cipher.ENCRYPT_MODE, key);
45 byte[] plainText = texto.getBytes(UNICODE_FORMAT);
46 byte[] encryptedText = cipher.doFinal(plainText);
47 criptografado = new String(Base64.encodeBase64(encryptedText));
48 } catch (Exception e) {
49 e.printStackTrace();
50 }
51 return criptografado;
52 }
53
54 public String descriptografa(String criptografado) {
55 String descriptografado = null;
56 try {
57 cipher.init(Cipher.DECRYPT_MODE, key);
58 byte[] encryptedText = Base64.decodeBase64(criptografado);
59 byte[] plainText = cipher.doFinal(encryptedText);
60 descriptografado = new String(plainText);
61 } catch (Exception e) {
62 e.printStackTrace();
63 }
64 return descriptografado;
65 }
66
67
68
69}