How to secure and retrieve string data with a consistent length using encryption and decryption in .NET

121 views Asked by At

We aspire to achieve encryption and decryption in a way that ensures the length of the encrypted result aligns with the length of the original data. How can this objective be accomplished in .NET code?

For example:

string chars = "abcdeABCDE12345"; int resLen = 6;

String to encrypt:: Hello Word!

Result: CE1b5h

1

There are 1 answers

5
GeorgeKarlinzer On

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)