encrypt c# code code example
Example 1: c# encrypt decrypt string
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
Example 2: encrypt in C#
using System;
using System.IO;
using System.Security.Cryptography;
class Class1
{
static void Main(string[] args)
{
byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
try
{
FileStream myStream = new FileStream("TestData.txt", FileMode.Open);
Aes aes = Aes.Create();
CryptoStream cryptStream = new CryptoStream(
myStream,
aes.CreateDecryptor(key, iv),
CryptoStreamMode.Read);
StreamReader sReader = new StreamReader(cryptStream);
Console.WriteLine("The decrypted original message: {0}", sReader.ReadToEnd());
sReader.Close();
myStream.Close();
}
catch
{
Console.WriteLine("The decryption failed.");
throw;
}
}
}