encrypt string with secret in csharp

Here's an example of how to encrypt a string using AES encryption in C# with a secret key:

main.cs
using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
    {
        byte[] encrypted;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (var msEncrypt = new System.IO.MemoryStream())
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
            {
                swEncrypt.Write(plainText);
                csEncrypt.FlushFinalBlock();
                encrypted = msEncrypt.ToArray();
            }
        }

        return encrypted;
    }

    static void Main(string[] args)
    {
        string plaintext = "Secret message to encrypt";
        byte[] key = Encoding.UTF8.GetBytes("mySecretKey12345");
        byte[] iv = Encoding.UTF8.GetBytes("mySecretIV1234567");

        byte[] encryptedBytes = EncryptStringToBytes(plaintext, key, iv);

        string encryptedString = Convert.ToBase64String(encryptedBytes);

        Console.WriteLine("Encrypted string: " + encryptedString);
    }
}
1300 chars
44 lines

This code uses an AES algorithm to encrypt a plain text string with a secret key and initialization vector (IV). The EncryptStringToBytes method takes in the plain text, key, and IV as parameters and returns the encrypted bytes. The Main method sets up the key and IV, calls the EncryptStringToBytes method, and converts the encrypted bytes to a base 64 string for printing to the console.

gistlibby LogSnag