It's possible with AES CFB mode.
Simple implementation:
static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
{
using var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CFB;
aes.Padding = PaddingMode.None;
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using var msEncrypt = new MemoryStream();
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using var swEncrypt = new StreamWriter(csEncrypt);
swEncrypt.Write(plainText);
}
return msEncrypt.ToArray();
}
static byte[] Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
using var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CFB;
aes.Padding = PaddingMode.None;
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using var msDecrypt = new MemoryStream(cipherText);
using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
using var msDecrypted = new MemoryStream();
csDecrypt.CopyTo(msDecrypted);
return msDecrypted.ToArray();
}
Usage:
var original = "Secret secret string";
using var aes = Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
var encrypted = Encrypt(original, aes.Key, aes.IV);
var decrypted = Decrypt(encrypted, aes.Key, aes.IV);
Note:
That solution encrypts and decrypts to bytes array, if your goal is to get a string you can convert it by Encoding.UTF8.GetString(bytes)
abcdefis UTF-8 encoded 6 bytes long, but the stringabcd€fis 8 bytes long. Therefore, specifying a length without encoding is incomplete. You may be referring to format-preserving encryption.