[英]C#: Base64 encoding
誰能讓我知道我在這段代碼中哪里出錯了? 此代碼是用 C#.NET 編寫的。 我需要使用 C#.NET 編寫一個使用 base64 格式對字符串進行編碼的算法,然后使用 PHP 使用 base64_decode() 進行解碼。 請看下面的片段:
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);
我認為您的代碼示例正在進行“加密”,而您想要“編碼”。 在 C# 中使用 Based64 編碼字符串,它應該如下所示:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
PHP 應該是這樣的:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
我需要使用 C#.net 編寫一個使用 base64 格式對字符串進行編碼的算法
這其實很容易。 您不需要復制粘貼代碼使用的所有密碼學內容。 以下就足夠了:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
string outputString = Convert.ToBase64String(bytes);
如果您打算通過 HTTP GET 請求將數據從 C# 發送到 PHP,請不要忘記對它進行 UrlEncode。 有關詳細信息,請參閱此問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.