public
class
Program
{
private
static
byte[]
cryptkey =
Encoding.ASCII.GetBytes("01234567890123456789abcdefabcdef");
private
static
byte[]
initVector = Encoding.ASCII.GetBytes("0123456789012359");
public
static
void
Main()
{
var
testo1 = "test";
var
testo2 = "pippo\n";
string
value = CryptAES(testo1);
Console.WriteLine("Crittare
'{0}'
produce: {1}",
testo1, CryptAES(testo1));
Console.WriteLine("Crittare
'{0}'
produce: {1}",
testo2, CryptAES(testo2));
Console.ReadLine();
}
public
static
string
DecryptAES(string
cipherData)
{
try
{
using
(var
rijndaelManaged =
new
RijndaelManaged
{ Key = cryptkey, IV = initVector, Mode = CipherMode.CBC
})
using
(var
memoryStream =
new
MemoryStream(Convert.FromBase64String(cipherData)))
using
(var
cryptoStream =
new
CryptoStream(memoryStream,
rijndaelManaged.CreateDecryptor(cryptkey,
initVector),
CryptoStreamMode.Read))
{
return
new
StreamReader(cryptoStream).ReadToEnd();
}
}
catch
(CryptographicException
e)
{
Console.WriteLine("A
Cryptographic error occurred: {0}",
e.Message);
return
null;
}
}
public
static
string
CryptAES(string
textToCrypt)
{
try
{
using
(var
rijndaelManaged =
new
RijndaelManaged
{ Key = cryptkey, IV = initVector, Mode = CipherMode.CBC
})
using
(var
memoryStream = new
MemoryStream())
using
(var
cryptoStream =
new
CryptoStream(memoryStream,
rijndaelManaged.CreateEncryptor(cryptkey,
initVector),
CryptoStreamMode.Write))
{
using
(var
ws = new
StreamWriter(cryptoStream))
{
ws.Write(textToCrypt);
}
return
Convert.ToBase64String(memoryStream.ToArray());
}
}
catch
(CryptographicException
e)
{
Console.WriteLine("A
Cryptographic error occurred: {0}",
e.Message);
return
null;
}
}
}