Encryption And Decryption Using A Symmetric Key(AES) using x++
Encryption And Decryption Using A Symmetric Key(AES) using x++.
I received a requirement to generate an XML file with encrypted data using a symmetric key. The recipients on the other side will decrypt the text using the same symmetric key. To test this, I used a dummy value such as 'RRR'.
To achieve this, I wrote the code in C# and added the resulting DLL to my project references.
C# Code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace EncryptionDecryptionUsingSymmetricKey
{
public class AesOperation
{
public static string EncryptString(string key, string plainText)
{
byte[] iv = new byte[16];
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(plainText);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);// It will convert bytes to string
}
public static string DecryptString(string key, string cipherText)
{
byte[] iv = new byte[16];
byte[] buffer = Convert.FromBase64String(cipherText); // It will convert string to bytes
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(buffer))
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
}
}X++ Code:
b14ca5898a4e4133bbce2ea2315a1916
Using EncryptionDecryptionUsingSymmetricKey;
internal final class TestRunnableClass1
{
public static void main(Args _args)
{
str key = "b65ff7654brt8799fghj4ed7892b6798";
str text = 'RRR';
str encryptedString = AesOperation::EncryptString(key, text);
info(encryptedString);
str decryptedString = AesOperation::DecryptString(key, encryptedString);
info(decryptedString);
}
}References Ref1 Ref2 and https://sheriffayed23.blogspot.com/2023/11/encryption-and-decryption-using.html





.png)