· 4 years ago · Mar 08, 2021, 11:46 AM
1import java.io.IOException;
2import java.io.UnsupportedEncodingException;
3import java.net.URI;
4import java.net.URLEncoder;
5import java.net.http.HttpClient;
6import java.net.http.HttpRequest;
7import java.net.http.HttpRequest.BodyPublishers;
8import java.net.http.HttpResponse;
9import java.net.http.HttpResponse.BodyHandlers;
10import java.nio.charset.StandardCharsets;
11import java.security.InvalidAlgorithmParameterException;
12import java.security.InvalidKeyException;
13import java.security.NoSuchAlgorithmException;
14import java.util.logging.Level;
15import java.util.logging.Logger;
16import javax.crypto.BadPaddingException;
17import javax.crypto.Cipher;
18import javax.crypto.IllegalBlockSizeException;
19import javax.crypto.NoSuchPaddingException;
20import javax.crypto.SecretKey;
21import javax.crypto.spec.IvParameterSpec;
22import javax.crypto.spec.SecretKeySpec;
23import java.util.Base64;
24import java.util.Random;
25public class AnnaTemplateNotification{
26 public static String Execute_WebService(){
27 try {
28 //Chave de desencriptação do web sevice cadastrado no AnnA
29 String DecKey = "OVZKTG+GPjKhMdpy+dPgwZRqruD9hB2/"; //Deve ser alterada conforme a empresa
30 //Chave de encriptação do web sevice cadastrado no AnnA
31 String EncKey = "gHS3TFSaDHpT0HtxZ/DO28/uYK/HL/SK"; //Deve ser alterada conforme a empresa
32 //Hash da empresa onde o template está cadastrado
33 String Hash = "A3EBA079";
34 //Criar novo IV
35 byte[] randomBytes = new byte[8];
36 new Random().nextBytes(randomBytes);
37 final IvParameterSpec IV = new IvParameterSpec(randomBytes);
38 String IVString = new String(Base64.getEncoder().encode(randomBytes));
39
40 //As chaves são geradas com encode em Base64, então é necessário realizar o decode para obter os bytes
41 byte[] decKeyDecoded = Base64.getDecoder().decode(DecKey);
42 byte[] encKeyDecoded = Base64.getDecoder().decode(EncKey);
43 //Após o decode é feito a associação aos tipos requeridos pelo algoritmo (SecretKey para as chaves)
44 SecretKey dKey = new SecretKeySpec(decKeyDecoded, "DESede");
45 SecretKey eKey = new SecretKeySpec(encKeyDecoded, "DESede");
46
47 //Encriptar os dados para envio via Web Service
48 String templateName = "templateTeste"; //Name do template a ser executado
49 String templateNameEncriptado = encrypt(templateName, eKey, IV); //Name do template encriptado
50 String templateNamespace = "template"; //Namespace do template a ser executado
51 String templateNamespaceEncriptado = encrypt(templateNamespace, eKey, IV); //Namespace do template encriptado
52
53 //Neste exemplo criaremos duas listas de telefones com macros diferentes para execução do template
54 String json = "[{";
55 json += "\"PhoneList\":\"950691561;914694745\",";
56 json += "\"Prop_Keys\":";
57 json += " [";
58 json += " {";
59 json += " \"PropName\":\"var1\",";
60 json += " \"PropValue\":\"AnnA\"";
61 json += " },";
62 json += " {";
63 json += " \"PropName\":\"var2\",";
64 json += " \"PropValue\":\"10/07/2021\"";
65 json += " }";
66 json += " ]},";
67 json += " {";
68 json += "\"PhoneList\":\"977225248;971195982\",";
69 json += "\"Prop_Keys\":";
70 json += " [";
71 json += " {";
72 json += " \"PropName\":\"var2\",";
73 json += " \"PropValue\":\"10/08/2021\"";
74 json += " }";
75 json += " ]";
76 json += "}]";
77 String templateDataEncriptado = encrypt(json, eKey, IV); //TemplateData encriptado
78
79 //Cria um lista com os dados do Web Service
80 String dadosPost = "HASH=" + URLEncoder.encode(Hash, StandardCharsets.UTF_8);
81 dadosPost += "&ANNAEXEC=" + URLEncoder.encode(IVString, StandardCharsets.UTF_8);
82 dadosPost += "&Name=" + URLEncoder.encode(templateNameEncriptado, StandardCharsets.UTF_8);
83 dadosPost += "&Namespace=" + URLEncoder.encode(templateNamespaceEncriptado, StandardCharsets.UTF_8);
84 dadosPost += "&TemplateData=" + URLEncoder.encode(templateDataEncriptado, StandardCharsets.UTF_8);
85
86 //Cria a requisição para o Web Service
87 HttpClient client = HttpClient.newHttpClient();
88 HttpRequest request = HttpRequest.newBuilder()
89 .uri(URI.create("https://itda.com.br/AnnA20/aannatemplatenotification.aspx")) //Caminho onde o AnnA está localizado
90 .header("Content-Type", "application/x-www-form-urlencoded")
91 .POST(BodyPublishers.ofString(dadosPost))
92 .build();
93
94 HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
95 String responseFromServer = response.body();
96
97 //Verifica se o texto do retorno do Web Service contém o IV enviado.
98 if (responseFromServer.contains(IVString))
99 {
100 //Separa os valores usando o IV enviado como separador
101 String novoIVEncriptado = responseFromServer.substring(responseFromServer.indexOf(IVString));
102 novoIVEncriptado = novoIVEncriptado.replace(IVString, "");
103 String retornoEncriptado = responseFromServer.substring(0, responseFromServer.indexOf(IVString));
104
105 //Desencripta o novo IV recebido com a chave de encriptação e o IV enviado
106 String novoIVString = decrypt(novoIVEncriptado, eKey, IV);
107
108 //O IV é gerado com encode em Base64, então é necessário realizar o decode para obter os bytes
109 byte[] ivDecoded = Base64.getDecoder().decode(novoIVString);
110 //Após o decode é feito a associação aos tipos requeridos pelo algoritmo (IvParameterSpec para o IV)
111 IvParameterSpec novoIV = new IvParameterSpec(ivDecoded);
112
113 //Desencripta o retorno com a chave de desencriptação e o novo IV
114 String retorno = decrypt(retornoEncriptado, dKey, novoIV);
115
116 //Retorna um JSON contendo a resposta do Web Service
117 return retorno;
118 }
119 else
120 {
121 //Retorna um JSON contendo a resposta do Web Service
122 return responseFromServer;
123 }
124 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | InterruptedException | IOException ex) {
125 Logger.getLogger(AnnaTemplateNotification.class.getName()).log(Level.SEVERE, null, ex);
126 return "Erro";
127 }
128 }
129 // Funções de encrypt e decrypt
130 public static String encrypt(String message, SecretKey key, IvParameterSpec iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
131 final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
132 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
133 byte[] plainTextBytes = message.getBytes("utf-8");
134 byte[] buf = cipher.doFinal(plainTextBytes);
135 byte[] base64Bytes = Base64.getEncoder().encode(buf);
136 String base64EncryptedString = new String(base64Bytes);
137 return base64EncryptedString;
138 }
139 public static String decrypt(String encMessage, SecretKey key, IvParameterSpec iv) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
140 byte[] message = Base64.getDecoder().decode(encMessage.getBytes("utf-8"));
141 final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
142 decipher.init(Cipher.DECRYPT_MODE, key, iv);
143 byte[] plainText = decipher.doFinal(message);
144 return new String(plainText, "UTF-8");
145 }
146}