【发布时间】:2017-01-21 03:44:32
【问题描述】:
我遇到了这个旧的 C# 代码,我想知道使用 .NET Framework 4.5 是否有更优雅和紧凑的东西来做同样的事情:加密文本,避免结果中出现 '=' 字符。
谢谢。
编辑:此外数字 40 的来源以及为什么不需要处理更长的文本?
public static string BuildAutoLoginUrl(string username)
{
// build a plain text string as username#AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
if (username.Length < 40)
{
//cycle to avoid '=' character at the end of the encrypted string
int len = username.Length;
do
{
if (len == username.Length)
{
username += "#";
}
username += "A";
len++;
} while (len < 41);
}
return @"http://www.domain.com/Account/AutoLogin?key=" + EncryptStringAES(username, sharedKey);
}
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize/8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize/8);
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
谢谢。
【问题讨论】:
-
为什么需要在输出中避免
=? -
不要删除等号。将它们编码到 URL 中。 msdn.microsoft.com/en-us/library/zttxte6w(v=vs.110).aspx
-
这里有实际问题需要解决吗?附加到字符串的代码长达十行,易于理解。
-
@Alberto read this about padding。编码必须是可解码的,因此使用“=”填充是 base 64 的实现方式。
-
您的更新是:“此外,数字 40 是从哪里来的,为什么不需要处理更长的文本?”所以你说的是你不明白这段代码是什么,或者为什么要实现它,但你正在考虑改变它。 不要那样做。首先了解代码的用途,然后尝试如果有充分的理由这样做,例如修复正确性或性能问题。我也看不懂,不过没打算改代码。
标签: c# asp.net asp.net-mvc encryption