[英]C#: Base64 encoding
Can anyone please let me know where I made a mistake in this code?谁能让我知道我在这段代码中哪里出错了? This code is written in C#.NET.
此代码是用 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.
我需要使用 C#.NET 编写一个使用 base64 格式对字符串进行编码的算法,然后使用 PHP 使用 base64_decode() 进行解码。 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);
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:
在 C# 中使用 Based64 编码字符串,它应该如下所示:
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 应该是这样的:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
I need to write an algorithm for encoding a string using base64 format using C#.net
我需要使用 C#.net 编写一个使用 base64 格式对字符串进行编码的算法
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.如果您打算通过 HTTP GET 请求将数据从 C# 发送到 PHP,请不要忘记对它进行 UrlEncode。 See this question for details:
有关详细信息,请参阅此问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.