Skip to content

Instantly share code, notes, and snippets.

@Kirill89
Created September 12, 2012 14:17
Show Gist options
  • Save Kirill89/3706895 to your computer and use it in GitHub Desktop.
Save Kirill89/3706895 to your computer and use it in GitHub Desktop.
AES-128
var str = "qwertyuio";
byte[] key = new byte[]{0,134,84,0,67,0,0,53,0,0,125,0,23,0,0,33};//Encoding.ASCII.GetBytes("1234567890123456");
var res = RpcClient.EncryptBytesAes(str, key, new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
Console.WriteLine(BitConverter.ToString(res));
Console.WriteLine(RpcClient.DecryptBytesAes(res, key, new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}));
public static byte[] EncryptBytesAes(string input, byte[] key, byte[] initialVector)
{
byte[] encrypted;
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.BlockSize = aesAlg.LegalBlockSizes[0].MinSize;
aesAlg.KeySize = aesAlg.LegalKeySizes[0].MinSize;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Key = key;
aesAlg.IV = initialVector;
aesAlg.Padding = PaddingMode.Zeros;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
public static string DecryptBytesAes(byte[] input, byte[] key, byte[] initialVector)
{
string plaintext = null;
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.BlockSize = aesAlg.LegalBlockSizes[0].MinSize;
aesAlg.KeySize = aesAlg.LegalKeySizes[0].MinSize;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Key = key;
aesAlg.IV = initialVector;
aesAlg.Padding = PaddingMode.Zeros;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(input))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment