title: Encrypt in C# Decrypt AES CBC 256
body: <p>I want encrypt in C# and decrypt in c++ but I have some Encoding problem :</p>
  
  <p>example variables  : </p>
  
  <p>Key : g<em>OtIPaL</em>ver—vS5UAnJbPqsDZSf,yJ1
  IVString : g<em>OtIPaL</em>ver—vS5</p>
  
  <p>my c# code : </p>
  
  <pre><code>public static string EncryptString(string message, string KeyString, string IVString)
      {
          byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString.Substring(0,32));
          byte[] IV = UTF8Encoding.UTF8.GetBytes(IVString);
  
          string encrypted = null;
          RijndaelManaged rj = new RijndaelManaged();
          rj.Key = Key;
          rj.IV = IV;
          rj.Mode = CipherMode.CBC;
          rj.Padding = PaddingMode.PKCS7;
          try
          {
              MemoryStream ms = new MemoryStream();
  
              using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
              {
                  using (StreamWriter sw = new StreamWriter(cs))
                  {
                      sw.Write(message);
                      sw.Close();
                  }
                  cs.Close();
              }
              byte[] encoded = ms.ToArray();
              encrypted = Convert.ToBase64String(encoded);
  
              ms.Close();
          }
          catch (CryptographicException e)
          {
              Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
              return null;
          }
          catch (UnauthorizedAccessException e)
          {
              Console.WriteLine("A file error occurred: {0}", e.Message);
              return null;
          }
          catch (Exception e)
          {
              Console.WriteLine("An error occurred: {0}", e.Message);
          }
          finally
          {
              rj.Clear();
          }
          return encrypted;
      }
  </code></pre>
  
  <p>When I try encrypt and my Key have some not ASCII char - count of bytes is more than lenght of string . </p>
  
  <p>How Encoding I shound use ? In C++ I use EVP (default padding is PKCS7) .</p>
  
  <pre><code>static string decryptEX(string KS, string ctext)
  {
  EVP_CIPHER_CTX* ctx;
  ctx = EVP_CIPHER_CTX_new();
  string IV = KS.substr(0, 16);
  int rc = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (byte*)&amp;KS[0], (byte*)&amp;IV[0]);
  std::string rtext;
  rtext.resize(ctext.size());
  
  int out_len1 = (int)rtext.size();
  rc = EVP_DecryptUpdate(ctx, (byte*)&amp;rtext[0], &amp;out_len1, (const byte*)&amp;ctext[0], (int)ctext.size());
  
  
  int out_len2 = (int)rtext.size() - out_len1;
  rc = EVP_DecryptFinal_ex(ctx, (byte*)&amp;rtext[0] + out_len1, &amp;out_len2);
  try
  {
      rtext.resize(out_len1 + out_len2);
  }
  catch (exception e)
  {
  
  }
  return rtext;
  </code></pre>
  
  <p>}</p>