using System.Security.Cryptography;
public static string encryptionKey = "cc1d7ddc4ab848888ed91c1cedf4dbd5";
private static string initialisationVector = "26744a68b53dd87bb395584c00f7290a";
public static void Main()
byte[] initVectorBytes = null;
initVectorBytes = Encoding.ASCII.GetBytes(encryptionKey);
Console.WriteLine("===== ddd: " + initVectorBytes.Length );
string ssss = EncryptText( "dddddasdf" );
int nLen = initialisationVector.Length;
byte[] convertArr = new byte[initialisationVector.Length / 2];
for (int i = 0; i < convertArr.Length; i++)
convertArr[i] = Convert.ToByte(initialisationVector.Substring(i * 2, 2), 16);
Console.WriteLine( convertArr.Length );
static public string EncryptText(string plainText)
using (RijndaelManaged myRijndael = new RijndaelManaged())
myRijndael.KeySize = 256;
myRijndael.BlockSize =256;
myRijndael.Key = Encoding.ASCII.GetBytes(encryptionKey);
myRijndael.IV = Encoding.ASCII.GetBytes(initialisationVector);
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
string encString = Convert.ToBase64String(encrypted); return encString;
static protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
using (RijndaelManaged rijAlg = new RijndaelManaged())
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
swEncrypt.Write(plainText);
encrypted = msEncrypt.ToArray();
public static void GenerateKeyAndIV()
RijndaelManaged myRijndaelManaged = new RijndaelManaged();
myRijndaelManaged.Mode = CipherMode.CBC;
myRijndaelManaged.Padding = PaddingMode.PKCS7;
myRijndaelManaged.GenerateIV();
myRijndaelManaged.GenerateKey();
string newKey = ByteArrayToHexString(myRijndaelManaged.Key);
string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
protected static byte[] HexStringToByte(string hexString)
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
public static string ByteArrayToHexString(byte[] ba)
StringBuilder hex = new StringBuilder(ba.Length * 2);
hex.AppendFormat("{0:x2}", b);