Exemplos
Abaixo temos alguns exemplos de implementação da integração com AnnA Web Services
string decKey = "DECRYPTION_KEY"; string encKey = "ENCRYPTION_KEY"; string IV = form.Get("ANNAEXEC"); // IV that AnnA will send to you
// Get post variables values (if any) string anotherVar = Decrypt3DES(form.Get("AnotherVar"), decKey, IV);
string containers = JsonConvert.SerializeObject( new List<object> { new { PropName = "Container001", PropValue = new List<object> { new { PropName = "Type", PropValue = "MESSAGE" }, new { PropName = "Phrase", PropValue = "The value of AnotherVar is: " + anotherVar } } } } );
// Generate new IV TripleDESCryptoServiceProvider cryptoServiceProvider = new TripleDESCryptoServiceProvider(); cryptoServiceProvider.GenerateIV(); string newBase64IV = Convert.ToBase64String(cryptoServiceProvider.IV);
string encryptedContainers = Encrypt3DES(containers, encKey, newBase64IV); string newEncryptedBase64IV = Encrypt3DES(newBase64IV, decKey, IV);
var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent(encryptedContainers + IV + newEncryptedBase64IV, Encoding.UTF8, "text/plain");
return response;
string decKey = "DECRYPTION_KEY"; string encKey = "ENCRYPTION_KEY"; string IV = Request.Form["ANNAEXEC"]; // IV that AnnA will send to you
// Get post variables values (if any) string anotherVar = Decrypt3DES(Request.Form["AnotherVar"], decKey, IV);
string containers = JsonConvert.SerializeObject( new List<object>() { new { PropName = "Container001", PropValue = new List<object>() { new { PropName = "Type", PropValue = "MESSAGE" }, new { PropName = "Phrase", PropValue = ("The value of AnotherVar is: " + anotherVar) } } } } );
// Generate new IV var cryptoServiceProvider = TripleDES.Create(); cryptoServiceProvider.GenerateIV();
string newBase64IV = Convert.ToBase64String(cryptoServiceProvider.IV); string encryptedContainers = Encrypt3DES(containers, encKey, newBase64IV); string newEncryptedBase64IV = Encrypt3DES(newBase64IV, decKey, IV);
return encryptedContainers + IV + newEncryptedBase64IV;
try { String decKey = "DECRYPTION_KEY"; String encKey = "ENCRYPTION_KEY"; String receivedIv = request.getParameter("ANNAEXEC"); // IV that AnnA will send to you
// Get post variables values (if any) String anotherVar = request.getParameter("AnotherVar");
byte[] ivDecoded = Base64.getDecoder().decode(receivedIv); byte[] decKeyDecoded = Base64.getDecoder().decode(decKey); byte[] encKeyDecoded = Base64.getDecoder().decode(encKey);
IvParameterSpec iv = new IvParameterSpec(ivDecoded); SecretKey dKey = new SecretKeySpec(decKeyDecoded, "DESede"); SecretKey eKey = new SecretKeySpec(encKeyDecoded, "DESede");
String decrypted = decrypt(anotherVar, dKey, iv);
String finalResponse = "[{"; finalResponse += "\"PropName\":\"Container001\","; finalResponse += "\"PropValue\":\""; finalResponse += " ["; finalResponse += " {"; finalResponse += " \\\"PropName\\\":\\\"Type\\\","; finalResponse += " \\\"PropValue\\\":\\\"MESSAGE\\\""; finalResponse += " },"; finalResponse += " {"; finalResponse += " \\\"PropName\\\":\\\"Phrase\\\","; finalResponse += " \\\"PropValue\\\":\\\"The value of AnotherVar is: \\\"" + decrypted + "\\\""; finalResponse += " }"; finalResponse += " ]\""; finalResponse += "}]";
byte[] randomBytes = new byte[8]; new Random().nextBytes(randomBytes); final IvParameterSpec newIv = new IvParameterSpec(randomBytes); String newEncodedIv = new String(Base64.getEncoder().encode(randomBytes));
finalResponse = encrypt(finalResponse, eKey, newIv); String newEncryptedIv = encrypt(newEncodedIv, dKey, iv); finalResponse = finalResponse + receivedIv + newEncryptedIv;
PrintWriter out = response.getWriter(); out.print(finalResponse);} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException ex) { Logger.getLogger(DESExample.class.getName()).log(Level.SEVERE, null, ex);}
function __output_header__($_data) { header('Content-Type: application/json; charset=utf-8'); return $_data; }
if ($_SERVER['REQUEST_METHOD'] !== "POST") { __output_header__(false, "Invalid request method", null); }
$DecKey = 'DECRYPTION_KEY'; $EncKey = 'ENCRYPTION_KEY'; $ReceivedIv = $_POST['ANNAEXEC']; // IV that AnnA will send to you
// Get post variables values (if any) $MyVar1 = $_POST['AnotherVar']; $MyVar1 = decrypt3DES($MyVar1, $DecKey, $ReceivedIv);
$response = '['; $response .= ' {'; $response .= ' "PropName": "Container001",'; $response .= ' "PropValue": "[{\"PropName\":\"Type\",\"PropValue\":\"MESSAGE\"},{\"PropName\":\"Phrase\",\"PropValue\":\"The value of AnotherVar is: \"' + MyVar1 + '\"}]"' $response .= ' }' $response .= ']'
// Generate new IV $ivlen = openssl_cipher_iv_length('des-ede3-cbc'); $newIv = base64_encode(openssl_random_pseudo_bytes(8)); $response = encrypt3DES($response, $EncKey, $newIv);
$newEncryptedIv = encrypt3DES($newIv, $DecKey, $ReceivedIv);
$response = $response . $ReceivedIv . $newEncryptedIv;
die(__output_header__($response));
&DecKEY = 'DECRYPTION_KEY' &EncKEY = 'ENCRYPTION_KEY' &IVRecebido = &HTTPRequest.GetVariable(!'ANNAEXEC') // IV that AnnA will send to you
// &CryptoDecrypt is type of "CryptoSymmetricEncrypt" &CryptoDecrypt.Algorithm = CryptoEncryptAlgorithm.TripleDES &CryptoDecrypt.Key = &DecKEY &CryptoDecrypt.IV = &IVRecebido
// Get post variables values (if any) &MyVar1 = &HTTPRequest.GetVariable(!'AnotherVar') &MyVar1 = &CryptoDecrypt.Decrypt(&MyVar1)
&Sdt_PropsContainer = new()
&Sdt_PropsItem = new() &Sdt_PropsItem.PropName = !'Type' &Sdt_PropsItem.PropValue = !'MESSAGE'
&Sdt_PropsContainer.Add(&Sdt_PropsItem)
&Sdt_PropsItem = new() &Sdt_PropsItem.PropName = !'Phrase' &Sdt_PropsItem.PropValue = 'O valor de "AnotherVar" é: ' + &MyVar1 &Sdt_PropsContainer.Add(&Sdt_PropsItem) //Adiciono o Container
&Sdt_PropsToAnna = new() &Sdt_PropsItem = new() &Sdt_PropsItem.PropName = !'Container001' &Sdt_PropsItem.PropValue = &Sdt_PropsContainer.ToJson()
&Sdt_PropsToAnna.Add(&Sdt_PropsItem)
&response = &Sdt_PropsToAnna.ToJson() //JSON de resposta ao AnnA
// Generate new IV &CryptoEncrypt = new() &CryptoEncrypt.Algorithm = CryptoEncryptAlgorithm.TripleDES &CryptoEncrypt.Key = &EncKEY &response = &CryptoEncrypt.Encrypt(&response) &IVNovo = &CryptoEncrypt.IV
&IVNovoEncriptado = &CryptoDecrypt.Encrypt(&IVNovo)
&response = &response + &IVRecebido + &IVNovoEncriptado
&HTTPResponse.AddString(&response)
from flask import Flask, request, Response from flask_ngrok import run_with_ngrok import json from Crypto.Cipher import AES, DES3, DES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes from base64 import b64encode, b64decode
# Initialising a web application with flask app = Flask(__name__)
# For this integration example, NGROK was used to emulate a response server run_with_ngrok(app)
# Encryption method def encrypt(data, enckey, iv): enckey = b64decode(enckey) iv = b64decode(iv) cipher = DES3.new(enckey, DES3.MODE_CBC, iv) ct_bytes = cipher.encrypt( pad(bytes(data, encoding='utf-8'), DES3.block_size)) ciphertext = b64encode(ct_bytes).decode('utf-8')
return ciphertext
# Decryption method def decrypt(data, deckey, iv): try: deckey = b64decode(deckey) iv = b64decode(iv) data = b64decode(data) cipher = DES3.new(deckey, DES3.MODE_CBC, iv) pt = unpad(cipher.decrypt(data), DES3.block_size)
return pt
except (ValueError, KeyError): return 'Incorrect decryption'
# Get POST AnnA @app.route('/get-post', methods=['POST']) def receber_post():
# Encryption Keys enckey = 'ENCRYPTION_KEY' deckey = 'DECRYPTION_KEY'
# Retrieving the form sent by AnnA data = request.form
# Recovering the received IV ivReceived = data.get('ANNAEXEC')
# Creating the structure of an AnnA message nodeMessage = [ { "PropName": "Alias", "PropValue": "msg001" }, { "PropName": "Type", "PropValue": "MESSAGE" }, { "PropName": "Phrase", "PropValue": "Hello World!" } ]
# Creating the container structure container = [ { "PropName": "Container001", "PropValue": json.dumps(nodeMessage) } ]
# Creating a new IV and encrypting it key = get_random_bytes(8) cipher = DES.new(key, DES3.MODE_CBC) newIV = b64encode(cipher.iv).decode('utf-8')
# Serialising the container structure and encrypting it serialisedContainer = json.dumps(container) encryptedSerialisedContainer = encrypt(serialisedContainer, enckey, newIV)
# Encrypting the new IV newIVEncrypted = encrypt(newIV, deckey, ivReceived)
# Configuring response for AnnA replyToAnnA = encryptedSerialisedContainer + ivReceived + newIVEncrypted
# Replying to AnnA response = Response(replyToAnnA, content_type='text/plain')
# Log print('\nData received from AnnA:', data) print('\nIV Received:', ivReceived) print('\n') print('\nNode Message:', nodeMessage) print('\nContainer:', container) print('\nContainer Serialised:', serialisedContainer) print('\nContainer Serialised Encrypted:', encryptedSerialisedContainer) print('\n') print('\nNew IV:', newIV) print('\nNew IV Encrypted:', newIVEncrypted) print('\n') print('\nReply To AnnA:', replyToAnnA) print('\nResponse From AnnA:', response)
return response
if __name__ == '__main__': app.run()