Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

php - C#: Base64 encoding

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
 ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...