有时 C# 中的 Base 64 无效字符
本文关键字:无效 字符 Base 中的 有时 | 更新日期: 2023-09-27 18:36:49
我正在用 c# asp.net 开发一个处理保留信息的应用程序。
出于这个原因,我做了一些研究,并在本教程中分别从 c# 提出了以下两个用于加密和解密的函数:
http://www.aspsnippets.com/Articles/AES-Encryption-Decryption-Cryptography-Tutorial-with-example-in-ASPNet-using-C-and-VBNet.aspx
我已经验证了在某些情况下解密出错,例如
加密("a808XXX")不起作用
加密("A808XXX") 工作
加密("a631XXX")工作
加密("A631XXX") 不起作用
错误是:
base64 无效字符
我尝试应用替换语法但没有成功:
Request.QueryString["m"].ToString().Replace(" ", "+")
我在下面的代码,如何解决这个问题?
请帮助我,提前谢谢你。
public string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
错误消息:"base64 无效字符"很清楚。
调试:找到错误,在错误发生的位置,修复错误。不要只是开始尝试。
在加密后打印 Base64 字符串,并在解密之前再次打印。
比较寻找差异/损坏。
验证两个 Base64 字符串是否仅包含有效字符"A-Za-z/+",并且可能包含一个或两个尾随"="字符。
如果 Base64 字符串是查询字符串的一部分,则可能需要对其进行 URL 编码。
您至少必须替换字符 + 和/。
尝试类似的东西
.Replace("+", "-").Replace("/", "_");
显然,在解密之前,您必须做相反的事情。