为什么使用 base64 解码在 C# 中无法正常工作

本文关键字:常工作 工作 base64 解码 为什么 | 更新日期: 2023-09-27 18:30:52

我有两个方法"EncodePassword"和"DecodePassword"如下:

// Pass the password as a string, then return the encoded password
string EncodePassword(string password)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(password));
}
// Pass the encoded password, then return that as a string
string DecodePassword(string password)
{
    return Encoding.UTF8.GetString(Convert.FromBase64String(password));
}
编码密码方法

完美运行,但解码密码方法不能!
例如,当我尝试编码"testpassword"时,结果是"dGVzdHBhc3N3b3Jk",但是当我尝试解码"dGVzdHBhc3N3b3Jk"时,结果是一些像这样的问号" - , "。
那么请问问题出在哪里?

为什么使用 base64 解码在 C# 中无法正常工作

代码按预期工作。 首先加载字符串一定有问题 - 否则在处理生成的字符串时弄乱了编码。

[TestMethod]
public void EncodeAndDecodePwd()
{
  const string pwd = "testpassword";
  string encodedPassword = EncodePassword(pwd);
  string decodedPassword = DecodePassword(encodedPassword);
  string decodedPassword2 = DecodePassword("dGVzdHBhc3N3b3Jk");
  Assert.AreEqual(pwd, decodedPassword);
  Assert.AreEqual(pwd, decodedPassword2);
  Assert.AreEqual(encodedPassword, "dGVzdHBhc3N3b3Jk");
}

BR