Передайте строку XML из консольного приложения c # в сторонний API с шифрованием AES, откройте сокет SSL TCP и получите ответ обратно, а также создайте анализатор для шифрования XML - PullRequest
0 голосов
/ 11 июня 2018

Я пытаюсь передать сообщение XML из моего консольного приложения C # в сторонний API с использованием шифрования AES (Advance Encryption Security) и получить ответ с аутентификацией с помощью ключа и IV, а затем выполнить дешифрование и декодировать эту строку изатем необходимо создать синтаксический анализатор, который шифрует каждый раздел сообщения, так что мое консольное приложение и обратный конец с этим сторонним API.

Я написал свой код ниже, но я не знаю, какой потокя могу написать код, а также меня смущает то, как я могу открыть сокет SSL TCP и отправить сообщение с запросом в API!

Я написал здесь некоторый код, но мог бы использовать некоторую помощь.

Спасибо!

                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Net;
                using System.Net.Http;
               using System.Text;
                using System.Threading.Tasks;
              using System.Security.Cryptography;

           namespace ConsoleApp
               {
              public class Program
                {   
                public static void Main()
                  {
                 try
                  {
                   const string xmlString =
           @"< Message >
                   < Request >
                    < Detail >
                  < TranType > Credit </ TranType >
                      < TranAction > Sale </ TranAction >
                      < Amount > 15.67 </ Amount >
                      < CurrencyCode > 840 </ CurrencyCode >
                    </ Detail >
                    < IndustryData >
                      < Industry > CardNotPresent </ Industry >
                      < Eci > 7 </ Eci >
                      < MarketSpecificId > B </ MarketSpecificId >
                    </ IndustryData >
                    < Account >
                      < Pan > 4111111111111111 </ Pan >
                      < Expiration > 1117 </ Expiration >
                      < Postal > 197222234 </ Postal >
                      < Address > 123 Fake Street</Address>
                    </Account>
                    <Authentication>
                    <Client>ABC</Client>
                    <Source>xyz</Source>
                    </Authentication>
                  </Request>
            </Message>";

            // Create a new instance of the Aes class. This generates a new key and initialization vector (IV). 
            using (Aes myAes = Aes.Create())
            {

                // Encrypt the string to an array of bytes.
                var algoKey = ConvertHexStringToByteArray("8FDFC56F3F87C9BD53A58C34BEBE27CABC4944BF26A711E5539F03742033F270");
                var algoIv = ConvertHexStringToByteArray("B751B5FCAC067336D2E7CEEBF9CF590D");

                byte[] myAes.Key = algoKey;
                byte[] myAes.IV = algoIv;

                byte[] encrypted = EncryptStringToBytes_Aes(xmlString, myAes.Key, myAes.IV);
                string base64 = Convert.ToBase64String(encrypted);

                 XDocument message = new XDocument(
                        new XElement("Message",
                        new XElement("Request", base64),
                        new XElement("Authentication",
                        new XElement("Client", "ABC"),
                        new XElement("Source", "XYZ")))
            );
        //transmit to api


        var t = new Task(HTTPS_POST);
        t.Start();
        t.Start();
        Console.Write(message);
        Console.ReadKey();

                // Decrypt the bytes to a string.
                string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);

                //Display the original data and the decrypted data.
                Console.WriteLine("Round Trip: {0}", roundtrip);
                console.ReadLine();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
    }

    private static async void HTTPS_POST()
    {
        const string apiUrl = "https://10.7.6.70";

        var handler = new HttpClientHandler
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false
        };

        // force tls 1.2
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = ((send, certificate, chain, sslPolicyErrors) => true);


        Console.WriteLine("Posting a credit transaction to: " + apiUrl);

        var client = new HttpClient(handler);
        var response = await client.PostAsync(apiUrl, new StringContent(message));

        var content = response.Content;

        Console.WriteLine("Response Status Code: " + (int)response.StatusCode);

        var result = await content.ReadAsStringAsync();

        if (result.Length > 50)
        {
            Console.WriteLine("Response: " + result);

            // TODO Decryption logic
        }
    }


    private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;
        // Create an Aes object with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;


            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }


        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

    private static byte[] ConvertHexStringToByteArray(string sHex)
    {
        byte[] yKey;

        try
        {
            // set byte length
            yKey = new byte[sHex.Length / 2];

            for (int i = 0, j = 0; j < yKey.Length; i += 2, j++)
            {
                yKey[j] = Convert.ToByte(sHex.Substring(i, 2), 16);
            }

        }
        catch (Exception e)
        {
            throw new Exception(e.Message, e);
        }

        return yKey;
    }

}

private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        // Declare the string used to hold
        // the decrypted text.
        string roundtrip = null;

        // Create an Aes object
        // with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        roundtrip = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return roundtrip;
    }
  }
...