· 5 years ago · Jun 09, 2020, 08:00 PM
1package des;
2import java.io.IOException;
3import java.io.PrintWriter;
4import java.io.UnsupportedEncodingException;
5import javax.servlet.ServletException;
6import javax.servlet.annotation.WebServlet;
7import javax.servlet.http.HttpServlet;
8import javax.servlet.http.HttpServletRequest;
9import javax.servlet.http.HttpServletResponse;
10import java.security.InvalidAlgorithmParameterException;
11import java.security.InvalidKeyException;
12import java.security.NoSuchAlgorithmException;
13import java.util.logging.Level;
14import java.util.logging.Logger;
15import javax.crypto.BadPaddingException;
16import javax.crypto.Cipher;
17import javax.crypto.IllegalBlockSizeException;
18import javax.crypto.NoSuchPaddingException;
19import javax.crypto.SecretKey;
20import javax.crypto.spec.IvParameterSpec;
21import javax.crypto.spec.SecretKeySpec;
22import java.util.Base64;
23import java.util.Random;
24@WebServlet("/DESExample")
25public class DESExample extends HttpServlet {
26 private static final long serialVersionUID = 1L;
27 public DESExample() {
28 super();
29 }
30 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31 try {
32 // Chave de desencriptação do websevice cadastrado no AnnA
33 String decKey = "UqOKIBu82BMiz4hEh+TqJpobsO9DonWo"; // Deve ser alterada conforme o cadastro do Web Service em sua empresa
34 // Chave de encriptação do websevice cadastrado no AnnA
35 String encKey = "tfR/F6ZhqVIFQ+2LNWTf+/dAz3urb3sf"; // Deve ser alterada conforme o cadastro do Web Service em sua empresa
36 // Ler a vari�vel de POST "ANNAEXEC" que contém o "IV Recebido" sem encriptação
37 String ivRecebido = request.getParameter("ANNAEXEC");
38 // Todas as demais varáveis recebidas no POST, com exceção da variável ANNAEXEC que contém o "IV Recebido" serão enviadas com seu conteédo encriptado
39 // Leitura da variável 'AnotherVar' enviada no POST encriptada
40 String anotherVar = request.getParameter("AnotherVar");
41 // O iv e as chaves são enviadas com encode em Base64, então é necessário realizar o decode para obter os bytes
42 byte[] ivDecoded = Base64.getDecoder().decode(ivRecebido);
43 byte[] decKeyDecoded = Base64.getDecoder().decode(decKey);
44 byte[] encKeyDecoded = Base64.getDecoder().decode(encKey);
45 // Após o decode é feito a associação aos tipos requeridos pelo algoritmo (IvParameterSpec para o IV, SecretKey para as chaves)
46 IvParameterSpec iv = new IvParameterSpec(ivDecoded);
47 SecretKey dKey = new SecretKeySpec(decKeyDecoded, "DESede");
48 SecretKey eKey = new SecretKeySpec(encKeyDecoded, "DESede");
49 // Desencriptação do conteúdo de 'AnotherVar'
50 String decrypted = decrypt(anotherVar, dKey, iv);
51 // ... Código do Web Service.
52 // Neste exemplo retornaremos um container tipo MSG com o valor desencriptado da vari�vel enviada no POST 'AnotherVar'
53 String finalResponse = "[{";
54 finalResponse += "\"PropName\":\"Container001\",";
55 finalResponse += "\"PropValue\":\"";
56 finalResponse += " [";
57 finalResponse += " {";
58 finalResponse += " \\\"PropName\\\":\\\"Type\\\",";
59 finalResponse += " \\\"PropValue\\\":\\\"MESSAGE\\\"";
60 finalResponse += " },";
61 finalResponse += " {";
62 finalResponse += " \\\"PropName\\\":\\\"Phrase\\\",";
63 finalResponse += " \\\"PropValue\\\":\\\"O valor de AnotherVar é: \\\" + decrypted + \\\"";
64 finalResponse += " }";
65 finalResponse += " ]\"";
66 finalResponse += "}]"
67 // ... Fim do código do Web Service.
68 // Encriptação do JSON de resposta ao AnnA
69 // Gerando um novo IV
70 byte[] randomBytes = new byte[8];
71 new Random().nextBytes(randomBytes);
72 final IvParameterSpec novoIv = new IvParameterSpec(randomBytes);
73 String novoIvEncoded = new String(Base64.getEncoder().encode(randomBytes));
74 // Encriptação do "IV Novo" com a chave de desencriptação e o "IV Recebido"
75 finalResponse = encrypt(finalResponse, eKey, novoIv);
76 String novoIvEncriptado = encrypt(novoIvEncoded, dKey, iv);
77 // Concatenação do JSON de resposta encriptado, o "IV Recebido" e o "IV Novo Encriptado"
78 finalResponse = finalResponse + ivRecebido + novoIvEncriptado;
79 // Envio das informações ao AnnA
80 PrintWriter out = response.getWriter();
81 out.print(finalResponse);
82 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException ex) {
83 Logger.getLogger(DESExample.class.getName()).log(Level.SEVERE, null, ex);
84 }
85 }
86 // Funções de encrypt e decrypt
87 public String encrypt(String message, SecretKey key, IvParameterSpec iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
88 final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
89 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
90 byte[] plainTextBytes = message.getBytes("utf-8");
91 byte[] buf = cipher.doFinal(plainTextBytes);
92 byte[] base64Bytes = Base64.getEncoder().encode(buf);
93 String base64EncryptedString = new String(base64Bytes);
94 return base64EncryptedString;
95 }
96 public String decrypt(String encMessage, SecretKey key, IvParameterSpec iv) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
97 byte[] message = Base64.getDecoder().decode(encMessage.getBytes("utf-8"));
98 final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
99 decipher.init(Cipher.DECRYPT_MODE, key, iv);
100 byte[] plainText = decipher.doFinal(message);
101 return new String(plainText, "UTF-8");
102 }
103}