我创建了一些用于加密和解密的方法和类,并为AES算法生成了随机密钥。现在,当我想使用随机密钥进行加密时,我的解密结果和输入字符串不匹配。并且当我使用指定的密钥时(不使用随机)匹配此结果,但在解密结果字符串
后有“ \ v”表达式我的随机密钥生成器工厂:
public class KeyGeneratorFactory
{
public static string keyGeneratorFactory()
{
string keyGenerator = string.Empty;
Random random = new Random();
int rdmkey = random.Next();
keyGenerator = "llkj322km,n3kl4nnl@" + Convert.ToString(rdmkey);
return keyGenerator;
}
}
这是我的加密方法
public static string EncryptPass(string password)
{
if (password == null)
{
return null;
}
else
{
byte[] bytePassword = Encoding.UTF8.GetBytes(password);
using (Aes aesEncryptor = Aes.Create())
{
Rfc2898DeriveBytes rf = new Rfc2898DeriveBytes(KeyGeneratorFactory.keyGeneratorFactory(), new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
aesEncryptor.Key = rf.GetBytes(32);
aesEncryptor.IV = rf.GetBytes(16);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(memoryStream, aesEncryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytePassword, 0, bytePassword.Length);
cs.Close();
}
password = Convert.ToBase64String(memoryStream.ToArray());
}
}
return password;
}
}
这是我的解密方法
public static string DecryptPass(string cypherPassword)
{
if (cypherPassword == null)
{
return null;
}
else
{
byte[] cypherPasswordByte = Convert.FromBase64String(cypherPassword);
using (Aes aesDecryptor = Aes.Create())
{
aesDecryptor.Padding = PaddingMode.Zeros;
Rfc2898DeriveBytes rf = new Rfc2898DeriveBytes(KeyGeneratorFactory.keyGeneratorFactory(), new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
aesDecryptor.Key = rf.GetBytes(32);
aesDecryptor.IV = rf.GetBytes(16);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(memoryStream, aesDecryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cypherPasswordByte, 0, cypherPasswordByte.Length);
}
cypherPassword = Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
return cypherPassword;
}
}
我想知道如何在字符串后清除“ \ v”,以及如何在不为用户保存数据库的情况下将随机密钥用于AES算法。我可以吗?我不喜欢使用指定的密钥