我有以下代码对密码字段进行编码,但当密码字段超过十个字符时会出错。
private string base64Encode(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];
//encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
这是解码编码值的代码
public string base64Decode(string sData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(sData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
请您参考如下方法:
该代码本身不应该失败 - 但它实际上并没有为密码提供任何保护。我不确定您真正想要执行的是哪种“编码”,但这不是执行此操作的方法。问题:
- 即使这行得通,从安全角度来看也很糟糕 - 这不是加密、散列或类似的东西
- 您无缘无故地分配了一个新的字节数组 - 为什么?
- 您正在捕获
Exception,这几乎总是是个坏主意 - 您的方法忽略了 .NET 命名约定
如果您能向我们解释大局是什么,我们可能会建议更好的方法。
我的猜测是,当您调用 Convert.FromBase64String 时,您看到的异常实际上是,即在等效的解码 方法中,您还没有向我们展示。
