I wrote a program in .NET 7 that encrypts a string and returns another string that contains the encrypted form of the first string. The problem is the program does not return anything, only a null string
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
internal class Program
{
private static void Main(string[] args)
{
string unencrypted = Console.ReadLine();
byte[] transformed = Encoding.UTF8.GetBytes(necriptat);
byte[] encrypted;
string cipher;
Aes aes = Aes.Create();
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform cryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);
CryptoStream cstream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write);
StreamWriter streamW = new StreamWriter(cstream);
streamW.Write(transformed);
encrypted = memoryStream.ToArray();
cipher = Encoding.UTF8.GetString(encrypted);
Console.WriteLine(cipher);
}
}
I want from this program to return a string containing the encrypted form of the first string. I would be thankful if you can help me to fix my problem
You missed synchronizing the buffer:
streamW.Write(transformed);
cstream.FlushFinalBlock(); <-- Here
encrypted = memoryStream.ToArray();