【问题标题】:Why decode using base64 not working correctly in C#为什么使用 base64 解码在 C# 中无法正常工作
【发布时间】:2014-11-18 11:30:31
【问题描述】:

我有两种方法“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));
}

EncodePassword 方法可以完美运行,但 DecodePassword 方法不行!
例如,当我尝试编码“testpassword”时,结果是“dGVzdHBhc3N3b3Jk”,但是当我尝试解码“dGVzdHBhc3N3b3Jk”时,结果是一些像这样的问号“��-��,�”。
请问是什么问题?

【问题讨论】:

  • 当我尝试代码时,它工作得很好。你怎么称呼这些方法?
  • 感谢 Guffa,重启 Visual Studio 和 Google Chrome 后问题解决(因为我在 asp.net 工作过)。

标签: c# base64 decode encode


【解决方案1】:

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

[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

【讨论】:

  • 为了完整性添加 Assert.AreEqual(encodedPassword, "dGVzdHBhc3N3b3Jk");
猜你喜欢
  • 2012-05-19
  • 2016-03-27
  • 2017-02-03
  • 2011-07-24
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多