gpt4 book ai didi

c# - 我的解密密码是 1 个字符

转载 作者:可可西里 更新时间:2023-11-01 11:24:35 29 4
gpt4 key购买 nike

所以我有这个加密/解密代码:

private string Crypt(string strData, string strPassword, bool bEncrypt)
{
byte[] u8_Salt = new byte[] { xxx };

PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(strPassword, u8_Salt);

Rijndael i_Alg = Rijndael.Create();
i_Alg.Key = i_Pass.GetBytes(32);
i_Alg.IV = i_Pass.GetBytes(16);

ICryptoTransform i_Trans = (bEncrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

MemoryStream i_Mem = new MemoryStream();
CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

byte[] u8_Data;
if (bEncrypt) u8_Data = Encoding.Unicode.GetBytes(strData);
else u8_Data = Convert.FromBase64String(strData);

try
{
i_Crypt.Write(u8_Data, 0, u8_Data.Length);
i_Crypt.Close();
}
catch { return null; }

if (bEncrypt) return Convert.ToBase64String(i_Mem.ToArray());
else return Encoding.Unicode.GetString(i_Mem.ToArray());

}

我试图改进它:

private string Crypt(string strData, string strPassword, bool bEncrypt)
{
byte[] u8Salt = new byte[] { xxx };

PasswordDeriveBytes iPass = new PasswordDeriveBytes(strPassword, u8Salt);

Rijndael iAlg = Rijndael.Create();
iAlg.Key = iPass.GetBytes(32);
iAlg.IV = iPass.GetBytes(16);

ICryptoTransform iTrans = (bEncrypt) ? iAlg.CreateEncryptor() : iAlg.CreateDecryptor();

MemoryStream iMem = new MemoryStream();
using (CryptoStream iCrypt = new CryptoStream(iMem, iTrans, CryptoStreamMode.Write))
{
byte[] u8Data;
try
{
if (bEncrypt)
u8Data = Encoding.Unicode.GetBytes(strData);
else
u8Data = Convert.FromBase64String(strData);



iCrypt.Write(u8Data, 0, u8Data.Length);
if (bEncrypt)
return Convert.ToBase64String(iMem.ToArray());
else
return Encoding.Unicode.GetString(iMem.ToArray());
}
catch (Exception e)
{
return null;
}
}
}

但我发现返回的解密密码太短了 1 个字符。我看不出这段新代码对前者有何错误。

最佳答案

您的using 语句将确保流被关闭并因此自动刷新。不幸的是,您从MemoryStream之前检索了密文/明文。


不要使用PasswordDeriveBytes,尤其不要超过20字节,这是不安全的。而是使用 `Rfc2898DeriveBytes .

关于c# - 我的解密密码是 1 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171625/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com