我遇到了这个旧的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;
}
感谢。
答案 0 :(得分:2)
等号是因为它是Base64编码字符串的一部分。它是Base64编码的,因为加密过程会产生一个字节数组,其中并非所有项都可以表示为可读文本。我想你可以尝试编码为Base64之外的其他东西,但是使用Base32或其他东西只会使得结果字符串更长,对于URL来说可能太长了。
答案 1 :(得分:0)
我已经使用&#34; Catto&#34;用户对此StackOverflow问题的回答:Encrypt and decrypt a string