2

Can anyone please let me know where I made a mistake in this code? This code is written in C#.NET. I need to write an algorithm for encoding a string using base64 format using C#.NET, and then decoded with base64_decode() using PHP. Please see the snippit below:

System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;

byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key);
byte[] keyBytes = new byte[16];

int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;

System.Array.Copy(pwdBytes, keyBytes, len);

rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;

System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

byte[] plainText = Encoding.UTF8.GetBytes(unencryptedString);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

return Convert.ToBase64String(cipherBytes);
Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
Prabhu M
  • 2,852
  • 8
  • 37
  • 54

2 Answers2

6

I think your code sample is doing "encryption", and you want "encoding". For encoding a string with Based64 in C#, it should look like this:

 static public string EncodeTo64(string toEncode)
    {
        byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
        string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }

And the PHP should look like this:

 <?php
  $str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
  echo base64_decode($str);
 ?>
Duke Hall
  • 582
  • 4
  • 12
  • 2
    Nice answer Duke. Strictly speaking you should access the GetBytes() method via 'System.Text.Encoding.ASCII.GetBytes(toEncode)' to avoid accessing to a static member of a type via a derived type. See [here](http://stackoverflow.com/questions/4945439/why-is-it-useful-to-access-static-members-through-inherited-types) for more info. – Dylan Hogg Oct 11 '12 at 00:18
0

I need to write an algorithm for encoding a string using base64 format using C#.net

That's actually quite easy. You don't need all that cryptography stuff that your copy-and-pasted code is using. The following suffices:

byte[] bytes = Encoding.UTF8.GetBytes(inputString);  
string outputString = Convert.ToBase64String(bytes);

If you plan to send the data from C# to PHP via a HTTP GET request, don't forget to UrlEncode it. See this question for details:

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519